Given a positive integer n 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 is not less than 2 and not larger than 58.
Assume that we have divided n into a parts, they are respectively n_1, n_2, …, n_a. Then we get a product
Now just choose an element ni which is greater than 4 from the set.
If n_i is even, we divide it into two parts:
else, we divide it into two parts:
And it’s clear that
So to get greater product, we would like to break
ni
n
i
into smaller pieces.
Above all, every piece in the set we get after breaking
n
n
<script type="math/tex" id="MathJax-Element-9">n</script> into many pieces should be smaller than or equal to 3. Of course, don’t choose 1 cause of anything’s production with 1 is itself.
How about 2? For example, 9 = 3 + 3 + 3 = 2 + 2 + 2 + 3
, and 3 * 3 * 3 = 27 > 2 * 2 * 2 * 3 = 24
.
int integerBreak(int n)
{
if(n == 2)return 1;
if(n == 3)return 2;
int temp = n / 3 * 3;
if(temp == n)return pow(3, n / 3);
if(n - temp == 1)return pow(3, n / 3 - 1) * 4;
return pow(3, n / 3) * 2;
}