题目:
Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.
示例:
given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).
题解:
这是一种经典的动态规划问题,顺着题目,很容易想到每一个状态f[i] = “i可以分拆成的最大积”,关键是怎么求得f[i]。实质上,对于i而言,我们将i分拆成两个数,j(1<=j<i)和i-j都可以进行三种情况的划分:
- (i-j)和j都不继续划分下去,得到i*(i-j)
- 只划分j,得到f[j]*(i-j)
- j与(i-j)都划分,得到f[j]*f[i-j]
最终从这三种情况中取得最大值(在实际编程中,第三种情况去掉,也能够得到正确的结果,原因有待进一步探究)
代码:
class Solution { public: int integerBreak(int n) { vector<int> dp(n+1,0); dp[0] = 0; dp[1] = 0; for(int i = 2;i<=n;i++) { int curr = 0; for(int j = 1;j<=i-1;j++) { curr = max(curr,j*(i-j)); //curr = max(curr,dp[j]*dp[i-j]); curr = max(curr,dp[j]*(i-j)); } dp[i] = curr; } return dp[n]; } };