标签:
leetcode343Integer Break
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.
Show Hint
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
class Solution { public: int function(vector<int> t) { int sum = 1; for (int i = 0; i < t.size(); ++i) { sum *= t[i]; } return sum; } int integerBreak(int n) { if (n <= 0) { return 0; } if (n == 1) { return 1; } vector<vector<int> > dp(n + 1, vector<int>()); dp[1].push_back(1); dp[2].push_back(1); dp[2].push_back(1); for (int i = 3; i < dp.size(); ++i) { vector<int> temp1 = dp[i - 2]; temp1.push_back(2); vector<int> temp2 = dp[i - 1]; temp2[0]++; sort(temp1.begin(), temp1.end()); sort(temp2.begin(), temp2.end()); if (function(temp1) > function(temp2)) { dp[i] = temp1; } else { dp[i] = temp2; } } return function(dp[n]); } };
标签:
原文地址:http://blog.csdn.net/guicaisa/article/details/51347610