343. Integer Break

来源:互联网 发布:jquery1.3.2.js 下载 编辑:程序博客网 时间:2024/06/02 02:16

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.


拆数,使得拆出来的数乘积最大。

乘积最大,例如拆成k份,要使得这些拆出来的数尽量平均,乘积才会大,那k怎么取呢?

遍历取吧,如果我们要求的乘积函数记为 F(k) ,那么这一定是一个先增后减的函数,只要取到最大就不用往下搜了

public static int integerBreak(int n){int max=0;for(int i=2;i<=n;i++){int base=n/i;int mod=n%i;int mul=1;for(int j=0;j<i;j++){if(j<mod)mul*=(base+1);else {mul*=base;}}if(mul>max)max=mul;else {break;}}return max;}


0 0