题目链接
问题描述
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.
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.
解题思路
简单地观察规律就可以知道只要拆分出足够多的3而且大于3的数拆分出的因子没有1即可。代码如下:
class Solution {
public:
int integerBreak(int n) {
if (n == 2) return 1;
if (n == 3) return 2;
int count = 0;
int temp = n;
while (temp > 4) {
temp -= 3;
count++;
}
int ret = 1;
while (count > 0) {
ret *= 3;
count--;
}
ret *= temp;
return ret;
}
};
难点在于为什么拆分出足够多的3就能得到最大值