Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 need to find the maximum 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.
Algorithm
To solve this, we will follow these steps ?
- Define a function dp() that takes parameter n
- If n is equal to 0, return 1
- Initialize ans := 0
- For i in range 1 to n + 1, calculate ans := maximum of ans and (i * dp(n - i))
- Return ans
- From the main method, return dp(n)
Example
Let us see the following implementation to get better understanding ?
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))
81
Optimized Solution with Memoization
The above recursive solution has overlapping subproblems. We can optimize it using memoization ?
class Solution:
def solve(self, n):
memo = {}
def dp(n):
if n == 0:
return 1
if n in memo:
return memo[n]
ans = 0
for i in range(1, n + 1):
ans = max(ans, i * dp(n - i))
memo[n] = ans
return ans
return dp(n)
# Test with different values
solution = Solution()
print("n =", 4, "? Product =", solution.solve(4))
print("n =", 8, "? Product =", solution.solve(8))
print("n =", 12, "? Product =", solution.solve(12))
n = 4 ? Product = 4 n = 8 ? Product = 18 n = 12 ? Product = 81
Mathematical Insight
For maximum product, we should prefer splitting into 3s when possible, as 3 gives the highest product per unit sum. For remainders, use 2s ?
def max_product_optimal(n):
if n <= 3:
return n - 1
# Use as many 3s as possible
if n % 3 == 0:
return 3 ** (n // 3)
elif n % 3 == 1:
return 3 ** (n // 3 - 1) * 4
else: # n % 3 == 2
return 3 ** (n // 3) * 2
# Compare both approaches
for n in [4, 8, 12, 15]:
print(f"n = {n}: Optimal = {max_product_optimal(n)}")
n = 4: Optimal = 4 n = 8: Optimal = 18 n = 12: Optimal = 81 n = 15: Optimal = 243
Conclusion
The recursive approach with memoization solves the problem efficiently. For optimal results, split the number into as many 3s as possible, using 2s for remainders to maximize the product.
