【LeetCode】343. Integer Break 整数拆分(Medium)(JAVA)
题目地址: https://leetcode.com/problems/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.
题目大意
给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。
说明: 你可以假设 n 不小于 2 且不大于 58。
解题方法
- 采用动态规划,用 dp[i] 表示 i 的最大取值
- 要计算 dp[i], 首先 dp[i] 之前的所有值都是已知的。那就从 [1, i - 1] 一个乘起来,计算最大值,乘的时候,要取 k 和 dp[k] 的最大值
class Solution {
public int integerBreak(int n) {
int[] dp = new int[n + 1];
dp[1] = 1;
for (int i = 2; i <= n; i++) {
int max = i / 2;
for (int j = 1; j <= max; j++) {
dp[i] = Math.max(dp[i], Math.max(j, dp[j]) * Math.max(i - j, dp[i - j]));
}
}
return dp[n];
}
}
执行耗时:1 ms,击败了61.61% 的Java用户
内存消耗:35.3 MB,击败了62.92% 的Java用户
![](https://i-blog.csdnimg.cn/blog_migrate/6c56d31f951aece27c5faae608dfac2e.jpeg)