算法题目 : 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 and not larger than 58.
算法分析:
这道题目讲的是给定给一个正整数n,将其分解成至少两个正整数的和,使这些整数的积最大化并且返回可以得到的最大乘积。
还是典型的dp问题,
dp[i]表示整数i拆分可以得到的最大乘积,则dp[i]只与dp[i - 2], dp[i - 3]两个状态有关
得到状态转移方程:
dp[x] = max(3 * dp[x - 3], 2 * dp[x - 2])
当x <= 3时,需要对结果进行特判。
算法代码(C++):
class Solution {
public:
int integerBreak(int n) {
int dp[n];
dp[1]=1;
dp[2]=1;
for(int i=3;i<=n;i++){
dp[i]=-1;
for(int j=1;j<i;j++){
dp[i]=max(j*dp[i-j],max(dp[i],j*(i-j)));
}
}
return dp[n];
}
};
class Solution {
public:
int integerBreak(int n) {
int dp[n];
dp[1]=1;
dp[2]=1;
for(int i=3;i<=n;i++){
dp[i]=-1;
for(int j=1;j<i;j++){
dp[i]=max(j*dp[i-j],max(dp[i],j*(i-j)));
}
}
return dp[n];
}
};