ID | Title | Difficulty | |
---|---|---|---|
Loading... |
343. Integer Break
Medium
LeetCode
Math, Dynamic Programming
Problem
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.
Code
当前的最大乘积
把当前数字拆分为两部分
两部分都是之前拆分的结果,比如把10拆分成3和7
找到dp[3],如果拆分3那么得到最大乘积是2,但是也可以选择直接用3本身,这样会让乘积更大
因此Math.max(j, dp[j])
对于7来说,选择dp[7]比7本身更大,因此最后选择3 * 12 = 36,得到结果
class Solution {
public int integerBreak(int n) {
int[] dp = new int[n + 1];
dp[1] = 1;
for(int i = 2; i <= n; i ++) {
for(int j = 1; j < i; j ++) {
dp[i] = Math.max(dp[i], Math.max(j, dp[j]) * Math.max(i - j, dp[i - j]));
}
}
return dp[n];
}
}
按 <- 键看上一题!
342. Power of Four
按 -> 键看下一题!
344. Reverse String