题目:
Given an integer n
, break it into the sum of k
positive integers, where k >= 2
, and maximize the product of those integers.
Return the maximum product you can get.
Example 1:
Input: n = 2 Output: 1 Explanation: 2 = 1 + 1, 1 × 1 = 1.
Example 2:
Input: n = 10 Output: 36 Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
Constraints:
2 <= n <= 58
思路:
dp题,dp[i]表示当前i可以被拆分相乘所得的最大值,那么转移公式是比i小的数j,max({ dp[i], j * dp[i - j], j * (i - j) }),这里dp[i]不用解释了;j * dp[i - j]相当于把i拆成j 和 i - j,当时这个i - j我们继续拆,拆成所能多个数,去获得它们的乘积,即我们用以前获取的dp值来计算;而j * (i - j)也是把i拆成j 和 i - j,但是i - j不拆了,直接把i 拆成两个数,然后相乘。搞清楚这个转移公式后就简单了,初始化的话因为n一定大于等于2,所以0和1都不用初始化,dp[2]只能拆1 * 1 = 1,然后顺序遍历即可。
代码:
class Solution {
public:
int integerBreak(int n) {
vector<int> dp(n + 1, 0);
dp[2] = 1;
for (int i = 3; i < n + 1; i++) {
for (int j = 1; j < i; j++) {
dp[i] = max({ dp[i], j * dp[i - j], j * (i - j) });
}
}
return dp[n];
}
};