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.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
题意就是讲一个整数分为若干个数(至少两个),使得这若干个数的乘积最大。利用动态规划不难求解,对于数n ,状态转移方程如下,复杂度o(n^2):
for(i=1 to n-1)
求出max{i*dp(n-i)}即可
//这里需要注意的是n<4时,要另外考虑
class Solution {
public:
int integerBreak(int n) {
vector<int> array(n);
array[0] = 1;
array[1] = 1;
array[2] = 2;
if (n == 1||n==2) {
return 1;
}
if (n == 3) {
return 2;
}
int max,temp;
for (int i = 4; i <= n; i++) {
max = 0;
for (int j = 1; j < i ; j++) {
if (i - j < 4) {
temp = i - j;
}
else {
temp = array[i - j - 1];
}
if (j*temp > max) {
max = j*temp;
}
}
array[i - 1] = max;
}
return array[n - 1];
}
};
但是有一个更优的解法时间复杂度为o(n),注意到:其实分解因子的时候每个因子都不会大于3
public class Solution {
public int integerBreak(int n) {
if(n==2) return 1;
if(n==3) return 2;
int product = 1;
while(n>4){
product*=3;
n-=3;
}
product*=n;
return product;
}
}