题目:
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.
Example 1:
Input: 2 Output: 1 Explanation: 2 = 1 + 1, 1 × 1 = 1.
Example 2:
Input: 10 Output: 36 Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
Note: You may assume that n is not less than 2 and not larger than 58.
题意:
题意很简单,将一个正整数拆分(插分成两个以上的正整数,这些正整数相加的和为原来的数)后相乘,求相乘的最大值。
解答:
首先,依照经验以及测试了几个数后可以判断
1. 将整数拆成尽量同样大小的数相乘,结果会比较大
2. 偶然发现,假设每次都尽量拆成同样的数,那么 拆分从小到大,乘积呈现一个山峰状,也就是存在一个极值,
例如对于10
1不考虑,2开始,2的五次方为32,之后3,3*3*4=36,之后4,4*4*2=32,之后5,5*5=25,之后6,6*4=24
32 36 32 25 24
我们可以看出这是一个山峰,所以我们只需要找到乘积在哪开始下降,就找到了最大点。
代码如下:
class Solution {
public int integerBreak(int n) {
if(n==2) return 1;
int pre,now;
pre=0;
for(int i=2;i<n;i++){
now = count(i,n);
if(pre>now){
break;
}
pre = now;
}
return pre;
}
public int count(int stub,int n){
int times=n/stub;
int l=n%stub;
if(l==0) return (int)Math.pow(stub,times);
else{
if((l+stub)>l*stub&×>1) return (int)Math.pow(stub,times-1)*(l+stub);
else return (int)Math.pow(stub,times)*l;
}
}
}