343. 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.
Example 1:
Input: 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.
Example 2:
Input: 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
- Note: You may assume that n is not less than 2 and not larger than 58.
Approach
- 题目大意给你一个数,问你某些数字合等于它并且它们的乘积最大是多少,看到这道题,如果之前有做个几个递推类的题目,那么这道题也就很容易就想到用递推来解决,然后这里我也还是用递推来解,我们设
dp[i]
,当数等于i
,它的最大乘机就为dp[i]
,所以就能想出递推公式dp[i]=max(dp[i],dp[i-j]*j),j<=i
,边界dp[0]=1
,因为每个数都要被减到零才能算出最大的乘机,但是又不能直接相乘零,所以只能设dp[0]=1
,不过题目有说n>=2
,就算没有,对n==0
做特殊判断就好。 - [WXM] LeetCode 416. Partition Equal Subset Sum C++以上的题也是用到递推的方法。
Code
class Solution {
public:
int integerBreak(int n) {
int c;
if (n % 2)c = n / 2 + 1;
else c = n / 2;
vector<int>dp(n + 1, 0);
dp[0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= c&&i >= j; j++) {
dp[i] = max(dp[i], dp[i - j] * j);
}
}
return dp[n];
}
};