343. Integer Break
Posted dysjtu1995
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了343. Integer Break相关的知识,希望对你有一定的参考价值。
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
以上是关于343. Integer Break的主要内容,如果未能解决你的问题,请参考以下文章