Integer 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.
但是这样复杂度是O(N^2)。
我们知道一个数分成两个最相近的数时,乘积最大上面可以优化为:
f(n) = f(n/2)f(n-n/2) 这样复杂度优化为O(N)
同时要注意n=2,n=3的时候情况,单独列出来。
class Solution {
public:
int integerBreak(int n) {
if(n==2) return 1;
if(n==3) return 2;
vector<int> Dp(n+1,0);
Dp[0] = 1;Dp[1] = 1;
Dp[2] = 2;Dp[3] = 3;
for(int i=4; i<=n; ++i){
Dp[i] = max(Dp[i/2]*Dp[i-i/2],max(Dp[i-3]*Dp[3],Dp[i-2]*Dp[2]));//两边尽量相等时乘积最大
}
return Dp[n];
}
};
本文介绍了一种使用动态规划方法解决整数分解为至少两个正整数之和并最大化乘积的问题。通过优化递推关系,将复杂度从O(N^2)降低到O(N),并特别讨论了n=2和n=3时的特殊情况。
1695

被折叠的 条评论
为什么被折叠?



