标签:int solution nat runtime run cto ble else sum
Problem:
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.
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 n is not less than 2 and not larger than 58.
思路:
Solution (C++):
int integerBreak(int n) {
vector<int> dp(n+1, 0);
if (n == 1) return 1;
dp[1] = 1;
dp[2] = 1;
for(int i = 3; i <= n; ++i) {
for (int j = 1; j <= i/2; ++j) {
dp[i] = max(dp[i], max(j*(i-j), j*dp[i-j]));
}
}
return dp[n];
}
性能:
Runtime: 0 ms??Memory Usage: 6.1 MB
思路:
Solution (C++):
int integerBreak(int n) {
if (n == 2) return 1;
else if (n == 3) return 2;
else if (n%3 == 0) return pow(3, n/3);
else if (n%3 == 1) return 2*2*pow(3, (n-4)/3);
else return 2*pow(3, (n-2)/3);
}
性能:
Runtime: 0 ms??Memory Usage: 6.1 MB
标签:int solution nat runtime run cto ble else sum
原文地址:https://www.cnblogs.com/dysjtu1995/p/12656340.html