1 题目
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.
2 尝试解
2.1 分析
N是2-58之间的整数,要求将其分解为若干正整数之和,问如何分解,这些正整数乘积最大。
结论是分解为2和3能够使乘积最大,且3越多越好。首先如果分解出来一个大于4的因子f,如果从中拆解出来一个2,则2*(f-2) = 2f - 4 > f,所以不可能有比4大的因子存在,否则可以继续拆解。分解出来4和分解出来2个2效果相通,所以因子只可能为1,2,3。如果能分解为3个2,那么也可以分解为2个3,但是3^2 > 2^3,分解为3更好。所以因子中最多只能有2个2。分解为1是最没效率的,要尽量避免。
N = 2 和 N = 3时是特殊情况。N > 3 时,若N%3 == 0 则全部分解为3,若N%3 == 2 则分解为1个2,其他全为3。若N%3 == 1则分解为2个2,其他全为3。
2.2 代码
class Solution {
public:
int integerBreak(int n) {
if(n == 2) return 1;
if(n == 3) return 2;
int three = (n % 3 == 1? n / 3 - 1 : n / 3);
int remain = n - 3*three;
return pow(3,three)*(remain?remain:1);
}
};
3 标准解
class Solution {
public:
long long integerBreak(long long n) {
if(n == 2) return 1;
if(n == 3) return 2;
if(n == 4) return 4;
if(n == 5) return 6;
if(n == 6) return 9;
return 3 * integerBreak(n - 3);
}
};