您的位置:首页 > 其它

leetcode-343. Integer Break

2016-04-28 22:55 239 查看
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.

思路:代码里有思路

class Solution {
public:
int integerBreak(int n) {
//先提结论,因式只能分解为2,3.这样结果最大
//2*(f-2) >= f 求出来f>=4.这说明任何大于等于4的因式都应该继续分解,那样最后的结果更大
//所以因式只能有2,3
//再由2*(f-2)>=3*(f-3)得出f<=5,只有<=5的数分解为2才行,5只能是2+3。所以只有4分解成2+2,其他的都优先分解3
//注意溢出,溢出返回0
if(n <= 1)
{
return 0;
}
if(n <=3)
{
return n-1;
}

long long result = 1;
while(n > 4)
{
result *= 3;
n -= 3;
}
result *= n;
if(result > INT_MAX)
{
return 0;
}
return (int)result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: