343. Integer Break
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.
很明显又是最优问题。
Dp的做法需要先枚举前5个值。
然后判断一下 max(*3,2*2)就好了。
不过这里用胡搞的方法更快!!!!!
(随便比较脏。。但是O(1)呀。。。。。。逃)
public class Solution { public int integerBreak( int n ) {
if(n<5){
if(n==1) return 0;
else if(n==2) return 1;
else if(n==3) return 2;
else{
return 4;
}
}
else{
int k = n/3;
int m = n%3;
Long ret = 1L;
ret = ( long )Math.pow( 3, k );
if(m==1){
ret=(ret / 3) * 4;
}else if(m==2){
ret*=m;
}
return ret.intValue();
}
} }