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
给定一个正整数 n ,将其拆分为 k 个 正整数 的和( k >= 2 ),并使这些整数的乘积最大化。
返回 你可以获得的最大乘积 。
示例 1:
输入: n = 2 输出: 1 解释: 2 = 1 + 1, 1 × 1 = 1。
示例 2:
输入: n = 10 输出: 36 解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。
提示:
2 <= n <= 58
| Language | Runtime | Memory | Submission Time |
|---|---|---|---|
| typescript | 72 ms | 42.5 MB | 2022/04/10 21:16 |
function integerBreak(n: number): number {
if (n === 2) {
return 1;
}
if (n === 3) {
return 2;
}
const dp: number[] = [];
dp[0] = 0;
dp[1] = 0;
dp[2] = 2;
dp[3] = 3;
for (let i = 2; i <= n; i++) {
for (let j = 2; j <= i / 2; j++) {
dp[i] = Math.max((dp[j] ?? 0) * (dp[i-j] ?? 0), (dp[i] ?? 0));
}
}
return dp[n];
};与 剑指 Offer 14- I. 剪绳子 一样。
思路: