难度中等1136收藏分享切换为英文接收动态反馈
给定一个正整数
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
class Solution {
public int integerBreak(int n) {
if(n==2)return 1;
int[] max = new int[]{0}; // 用于记录最大乘积
backtrack(n, 2, 1, max); // 调用回溯函数
return max[0]; // 返回最大乘积
}
// 回溯函数
private void backtrack(int n, int start, int product, int[] max) {
// 如果 n 等于 1,更新最大乘积并返回
if (n == 1) {
max[0] = Math.max(max[0], product);
return;
}
// 从起始值开始遍历,计算当前数和 n 的差值 remaining 和当前乘积乘以当前数得到的新乘积 newProduct
for (int i = start; i <= n; i++) {
int remaining = n - i;
int newProduct = product * i;
// 递归调用回溯函数,将 remaining、当前数 i 和新乘积 newProduct 传入
backtrack(remaining, i, newProduct, max);
// 计算新的最大乘积,并更新 max 数组的值
max[0] = Math.max(max[0], newProduct * remaining);
}
}
public static void main(String[] args) {
Solution solution = new Solution();
int n = 10;
int result = solution.integerBreak(n);
System.out.println("The maximum product for " + n + " is: " + result);
}
}
动态规划
class Solution {
public static int integerBreak(int n)
{
int []dp=new int[n+1];
dp[1]=dp[0]=0;
dp[2]=1;
for(int i=3;i<=n;i++)
for(int j=0;j<i;j++)
{
dp[i]=Math.max(Math.max((i-j)*j,j*dp[i-j]),dp[i]);
}
return dp[n];
}
public static void main(String[] args) {
Solution solution = new Solution();
int n = 2;
int result = solution.integerBreak(n);
System.out.println("The maximum product for " + n + " is: " + result);
}
}