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

相关链接如下:

知乎:littledy

欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/dysjtu1995/p/12656340.html