40. Integer Break
Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers.
Return the maximum product you can get.
Example 1:
Input: n = 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.Example 2:
Input: n = 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.Solution: (Recursion)
// Solution 1 :
class Solution
{
public:
long long int maxProd = 0;
void findMax(int sum, long long int prod, int num, int count, int maxNum)
{
if (sum == 0 && count >= 2)
{
maxProd = max(prod, maxProd);
return;
}
if (sum < 0)
{
return;
}
if (num > maxNum)
{
return;
}
findMax(sum, prod, num + 1, count, maxNum);
findMax(sum - num, prod * num, num, count + 1, maxNum);
return;
}
int integerBreak(int n)
{
findMax(n, 1, 1, 0, n);
return maxProd;
}
};
// Solution 2 :
class Solution
{
public:
long long int maxProd = 0;
void findMax(int sum, long long int prod, int count)
{
if (sum == 0 && count >= 2)
{
maxProd = max(prod, maxProd);
return;
}
if (sum < 0)
{
return;
}
for (int i = 1; i <=sum; i++)
{
findMax(sum - i, prod * i, count + 1);
}
return;
}
int integerBreak(int n)
{
findMax(n, 1, 0);
return maxProd;
}
};Solution: (Recursion + Memo)
Solution: (DP)
Last updated
Was this helpful?