Description
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.
分析
设d(i)是当n=i时的最大乘积。考虑n=10的情况,可以拆分成4和6,而6拆分为3和3,这样的乘积最大。但是上述6的拆分计算过程可以利用乘以d(6)来计算得出结果。
可以看出,计算出拆分整数的对应d(i)可以简化计算,也是动态规划的思想,至此可以写出下面的状态转移方程:
d(i)=d(j)*d(i-j)
但是,上述状态转移方程并不是正确的。因为对于某些i值,d(i)的值并不比i大。比如2,d(2)=1。那么对于拆分出2的整数来说,直接使用d(2)相乘是错误的,因为乘以了1,而题意显然要求的是乘以2。
所以,乘以d(i)来计算结果显然只适用于d(i)>=i的情况。其他时候需要乘以i。
基于以上思想,写出了如下代码:
代码
class Solution {
public:
int integerBreak(int n) {
int *dp = new int[n + 1];
for (int i = 0; i < n+1; i++) dp[i] = 1;
for (int i = 3; i < n+1; i++) {
for (int j = 1; j <= i / 2; j++) {
dp[i] = max(dp[i],
(dp[j] > j ? dp[j] : j) * (dp[i-j] > i-j ? dp[i-j] : i-j));
}
}
return dp[n];
}
};