码迷,mamicode.com
首页 > 其他好文 > 详细

343. Integer Break

时间:2020-04-07 22:40:21      阅读:74      评论:0      收藏:0      [点我收藏+]

标签: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

343. Integer Break

标签:int   solution   nat   runtime   run   cto   ble   else   sum   

原文地址:https://www.cnblogs.com/dysjtu1995/p/12656340.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!