您的位置:首页 > 其它

343. Integer Break

2017-01-01 15:06 274 查看
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).

试着找规律,发现拆成a*3+b*2的形式,乘积最大,其中a尽可能的大。

public class Solution {
public int integerBreak(int n) {
if(n==2) return 1;
if(n==3) return 2;
int count3=0;
int count2=0;
count3=n/3;
while(true){
if((n-3*count3)%2==0){
count2=(n-3*count3)/2;
break;
}
else
count3--;
}
return (int) (Math.pow(3, count3)*Math.pow(2, count2));
}
}动态规划:

public class Solution {
public int integerBreak(int n) {
int[] dp=new int[n+1];
dp[1]=1;
for(int i=2;i<=n;i++){
for(int j=1;j<i;j++){
dp[i]=Math.max(dp[i], Math.max(j, dp[j])*Math.max(i-j, dp[i-j]));
}
}
return dp
;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: