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.
Example 1:
Input: 2 Output: 1 Explanation: 2 = 1 + 1, 1 × 1 = 1.
Example 2:
Input: 10 Output: 36 Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
分析:
这道题标注在DP下但是貌似用简单的DP时间复杂度太高了。。O(n2)
D[i] = max(i, max(D[a],a)*max(D[b],b)) (其中a+b=i)
看了题目的提示应该有O(n)的解法,所以需要利用一点数学规律(分结成2/3,且越多3越好),证明就不说了,转移公式改为:
dp[i] = max(2 * dp[i - 2], 3 * dp[i - 3])
public static int integerBreak2(int n) {
if(n <= 3) return n - 1;
int[] dp = new int[n + 1];
dp[1] = 1;
dp[2] = 2;
dp[3] = 3;
for(int i = 4; i <= n; ++i)
{
dp[i] = Math.max(2 * dp[i - 2], 3 * dp[i - 3]);
}
return dp[n];
}
上面这个思路转化下,其实就是能分解为3,就尽可能分解为3,
分为下面几种情况:
n % 3 == 0 就全部分解为3。
n % 3 == 1 肯定有个4,剩下的分解为3。(4分结成2*2比1*3大)
n % 3 == 2 有个2,剩下的全部分解为3。
public int integerBreak(int n) {
if(n<=3)
return n-1;//n<=3不符合规律
else if(n%3==0)
return (int)Math.pow(3,n/3);//注意如果不强制转换会抛异常
else if(n%3==1)
return (int)Math.pow(3,(n-4)/3)*4;
else
return (int)Math.pow(3,(n-2)/3)*2;
}