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:
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.
**
Algorithm:
**
一开始用递归做,意料之中地超时了。
设F(k)为n=k时我们要得到的数,那么问题就可以化为以下的状态方程:
F(k)=MAX(i=4~k/2)(MAX((F(k-i)i,(k-i) i)),因为我们已知F(2)=1,F(3)=2
**
Code:
class Solution {
public:
int integerBreak(int n) {
if(n==2)
return 1;
if(n==3)
return 2;
int num[100];num[2]=1;num[3]=2;
for(int i=4;i<=n;i++)
{
int max=1;
for(int j=2;j<=i/2;j++)
{
int a=(i-j)*j;
int b=num[i-j]*j;
int c=a>b?a:b;
if(c>max)
max=c;
}
num[i]=max;
}
return num[n];
}
};