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.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/integer-break
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法一:动态规划。
dp[i]为i之前的所有位置,乘以剩下的数。
class Solution {
public int integerBreak(int n) {
if (n <= 3) {
return n - 1;
}
n++;
int []dp = new int[n + 1];
dp[1] = 1;
dp[2] = 1;
for (int i = 3; i <= n; i++) {
for (int j = 1; j < i; j++) {
dp[i] = Math.max(dp[i], dp[j] * (i - j));
}
}
return dp[n];
}
}
方法二:
按照规律,都是先把3给拆出来,然后再算。
数字4拆成 2+2,乘积最大,为4。
数字5拆成 3+2,乘积最大,为6。
数字6拆成 3+3,乘积最大,为9。
数字7拆为 3+4,乘积最大,为 12。
数字8拆为 3+3+2,乘积最大,为 18。
数字9拆为 3+3+3,乘积最大,为 27。
数字10拆为 3+3+4,乘积最大,为 36。
public class Solution {
public int integerBreak(int n) {
if (n == 2) {
return 1;
}
if (n == 3) {
return 2;
}
double ans;
int n3 = n / 3;
int sh= n % 3;
ans = Math.pow(3,n3);
if (sh == 1) {
ans = ans/ 3 * 4;
} else if (sh == 2) {
ans *= 2;
}
return (int)ans;
}
}
探讨如何将正整数n拆分为至少两个正整数之和,并最大化这些整数的乘积,通过动态规划和规律分析两种方法实现。
1707

被折叠的 条评论
为什么被折叠?



