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
;
}
}
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
;
}
}
相关文章推荐
- 343. Integer Break
- LeetCode[343] Integer Break
- 343. Integer Break
- LeetCode 343 Integer Break (数学)
- 343. Integer Break
- Leetcode Integer Break 343
- 动态规划2-Leetcode343-integerBreak
- 343. Integer Break
- leetcode343 Integer Break
- 343. Integer Break #Medium
- leetcode@ [343] Integer Break (Math & Dynamic Programming)
- 343. Integer Break
- leetcode343 Integer Break java
- leetcode:数学:Integer Break(343)
- [343]Integer Break
- 343. Integer Break
- 343. Integer Break
- 343. Integer Break
- 343. Integer Break
- 343. Integer Break