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.
解决方案:利用动态规划,设dp[ i ]为把i分为非负整数,这些整数乘积的最大值。
令dp[ 0 ]=1,
dp[ i ]=max{ max{j,dp[j] }, max{i-j,dp[i-j]} }, for 1<=j<=i/2.
代码如下:
class Solution {
public:
int integerBreak(int n) {
int *dp=new int[n+1];
int i,j,temp,result,m1,m2;
dp[0]=1;
for(i=1;i<=n;i++){
dp[i]=dp[i-1];
for(j=1;j<=i/2;j++){
m1=(i-j)>dp[i-j]?(i-j):dp[i-j];
m2=j>dp[j]?j:dp[j];
temp=m1*m2;
if(dp[i]<temp)
dp[i]=temp;
}
}
result=dp[n];
delete []dp;
return result;
}
};