Problem
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.
Note: You may assume that n is not less than 2 and not larger than 58.
Hint:
- There is a simple O(n) solution to this problem.
- You may check the breaking results of n ranging from 7 to 10 to discover the regularities.
Example
given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).
Algorithm
整理一下题意:给定一个整数n,将n分成至少两个正整数的和,将分成的整数乘起来得到一个积,要求返回积的最大值。假设2<=n<=58。
其实没有明确的思路,所以先尝试枚举。
n | 最大拆分 | 最大乘积 |
---|---|---|
2 | 1+1 | 1 |
3 | 1+2 | 2 |
4 | 2+2 | 4 |
5 | 2+3 | 6 |
6 | 3+3 | 9 |
7 | 3+4 | 12 |
8 | 3+3+2 | 18 |
9 | 3+3+3 | 27 |
由上表猜测,最大拆分中需要尽可能多的3。以此为思路,对于n的最大积,通过n每次减3和积每次乘3得到。代码如下。
//时间复杂度O(n)
class Solution {
public:
int integerBreak(int n) {
if(n==2) return 1;
if(n==3) return 2;
if(n==4) return 4;
int max=1;
while(n>4){
max*=3;
n-=3;
}
return max*n;
}
};
完成题目后提交,很幸运通过了。但对于其数学原理还是不明白,于是在网上查找资料,发现 @liyuanbhu 老师的博客里有简单的数学证明。下面将这段证明引用如下。感谢 @liyuanbhu 老师的工作!
原文地址:http://blog.csdn.net/liyuanbhu/article/details/51198124
作者:@liyuanbhu
首先证明拆出的因子大于 4 是不行的。设 x 是一个因子,x>4,那么可以将这个因子再拆成两个因子 x−2 和 2,易证 (x−2)×2>x。所以不能有大于 4 的因子。
4 这个因子也是可有可无的,4=2+2,4=2×2。因此 4 这个因子可以用两个 2 代替。
除非没有别的因子可用,1 也不能选作因子。一个数 x 当它大于 3 时,有 (x−2)×2>(x−1)×1。
这样呢,就只剩下 2 和 3 这两个因子可以选了。下面再证明 3 比 2 好。
一个数 x=3m+2n,那么 f=3m×2n=3m×2x−3m2 可以对它取个对数。
lnf===mln3+nln2mln3+x−3m2ln2x2ln2+(ln3−32ln2)m
其中 ln3−32ln2>0 所以 f 是 m 的增函数,也就是说 m 越大越好。所以 3 越多越好。再多说一句,如果拆出的因子不限于整数的话,可以证明e=2.718… 是最佳的选择。