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.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
分析:
如果n=2,最大的乘积就是1*1=1
如果n=3,最大的乘积就是1*2=2
如果n=4,最大的乘积就是2*2=4
如果n=5,最大的乘积就是3*2=6
…..
我们可以得到:
(n/2)*(n/2)>=n; if n>=4
((n+1)/2)*((n-1)/2)>=n; if n>=5
所以分解的factor<=4,即1,2,3,也就是2 or 3的问题了
根据n=6时,3*3>2*2*2, 我们选择3
代码
class Solution {
public int integerBreak(int n) {
int result=1;
if(n==2)return 1;
if(n==3)return 2;
if(n==4)return 4;
while(n>4){
n-=3;
result*=3;
}
return result*n;
}
}