【题目】
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.
For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).
Note: You may assume that n is not less than 2 and not larger than 58.
【题解】
令dp[n]为n对应的最大积。
那么递推方程就是:dp[n]=max(i*dp[n-i],i*(n-i))(其中i从1到n-1)。
边界:dp[2]=1;
时间复杂度:O(n2),由于题目中n的值最大为58,所以并不会出现超时的情况。
若n的值很大的话,动态规划的做法无法解决,仔细观察会发现该题有数学解法,详细请参考网上大神的题解点击打开链接
【代码】
int integerBreak(int n) {
vector<int> dp(n + 1);
dp[0] = 1;
dp[1] = 1;
dp[2] = 1;
for (int i = 3; i <= n; i++) {
for (int j = 1; j < i; j++) {
dp[i] = max(dp[i], max(dp[i - j] * j, (i - j) * j));
}
}
return dp[n];
}