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.

 1 class Solution {
 2 public:
 3     int integerBreak(int n) {
 4         vector<int> dp(n+1);
 5         dp[1] = 1;
 6         dp[2] = 1;
 7         for (int i = 3; i <= n; i++){
 8             dp[i] = -1;
 9             for (int j = 1; j<i; j++){
10                 dp[i] = max(j*dp[i - j], max(dp[i], j*(i - j)));
11             }
12         }
13         return dp[n];
14     }
15 };

 

posted on 2017-08-11 10:21  无惧风云  阅读(115)  评论(0编辑  收藏  举报