题目: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.
看到这道题,想着应该是可以通过前面的数推出后面的数的规律,于是把前几个数的拆分结果列出来,得下表:
数字 | 拆分结果 | 乘积 |
---|---|---|
2 | 1+1 | 1 |
3 | 2+1 | 2 |
4 | 2+2 | 4 |
5 | 3+2 | 6 |
6 | 3+3 | 9 |
7 | 3+4 | 12 |
8 | 3+3+2 | 18 |
9 | 3+3+3 | 27 |
10 | 3+3+4 | 36 |
11 | 3+3+3+2 | 54 |
12 | 3+3+3+3 | 81 |
观察上表可知,从5开始,数字都是先拆出3来,然后最后剩下小于等于4的数,然后乘起来,所以得代码如下:
class Solution {
public:
int integerBreak(int n) {
if(n == 2 || n == 3) {
return n-1;
}
int pro = 1;
while(n > 4) {
pro *= 3;
n -= 3;
}
pro *= n;
return pro;
}
};
再观察所得的结果,从数字7开始,其结果都是第i-3位的结果的三倍,于是可得解法二:
class Solution {
public:
int integerBreak(int n) {
vector<int> pro = {0,0,1,2,4,6,9};
for(int i = 7; i <= n ;i++) {
pro.push_back(pro[i-3]*3);
}
return pro[n];
}
};