Problem description:

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.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
https://goo.gl/CizU8W

Solution:

We can try to find the pattern,
num divide into product
2 1+1 1
3 2+1 2
4 2+2 4
5 2+3 6
6 3+3 9
7 3+2+2 12
8 3+3+2 18

We can see that, all factors should be 2 or 3 (N > 4). Also, since 3 * 3 > 2 * 2 * 2, we should try to have 3 as much as possible(N>4).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int integerBreak(int n) {
if(n ==2) return 1;
if(n==3) return 2;
int product =1;

while(n>4){
product *=3;
n-=3;
}
product *=n;

return product;
}
};