1.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.
2. Analysis
对于n来说,它可以被拆分为 n1 和 n2 的和,而 n1 和 n2 又可以被拆分为其他的和,最小一定是止于 n = 1,n = 2, n = 3这三者之中。(待我考完试再来仔细写明分析过程,其实很简单的)。时间复杂度为 O(n2)
状态转移方程:
dp[i]=max(dp[i−j]∗dp[j],(i−j)∗j,dp[i−j]∗j,(i−j)∗dp[j],dp[i]);
3. Code
class Solution {
public:
static int max(int a, int b, int c, int d, int origin) {
int t1 = (a >= b)? a : b;
int t2 = (c >= d)? c : d;
int t3 = (t1 >= t2) ? t1 : t2;
return t3 >= origin ? t3 : origin;
}
int integerBreak(int n) {
if(n == 2) return 1;
if(n == 3) return 2;
dp[1] = 1;
dp[2] = 1;
dp[3] = 2;
for(int i = 4; i <= n; i++) {
dp[i] = 0;
//这里可以改进一下,因为不需要遍历到 i-1,拆分i的左右两边是对称的
for(int j = 1; j < i; j++)
dp[i] = max(dp[i-j]*dp[j], (i-j)*j, dp[i-j]*j, (i-j)*dp[j], dp[i]);
}
return dp[n];
}
private:
int dp[60];
};