Program to find product of few numbers whose sum is given in Python


Suppose we have a number n, we have to find two or more numbers such that their sum is equal to n, and the product of these numbers is maximized, we have to find the product.

So, if the input is like n = 12, then the output will be 81, as 3 + 3 + 3 + 3 = 12 and 3 * 3 * 3 * 3 = 81.

To solve this, we will follow these steps −

  • Define a function dp() . This will take n

  • if n is same as 0, then

    • return 1

  • ans := 0

  • for i in range 1 to n + 1, do

    • ans := maximum of ans and (i * dp(n − i))

  • return ans

  • From the main method, do the following −

  • return dp(n)

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, n):
      def dp(n):
         if n == 0:
            return 1
         ans = 0
         for i in range(1, n + 1):
            ans = max(ans, i * dp(n - i))
         return ans
      return dp(n)
ob1 = Solution()
print(ob1.solve(12))

Input

12

Output

81

Updated on: 21-Oct-2020

158 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements