原题
给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。
示例 1:
输入: 2
输出: 1
解释: 2 = 1 + 1, 1 × 1 = 1。
示例 2:
输入: 10
输出: 36
解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。
说明: 你可以假设 n 不小于 2 且不大于 58。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/integer-break
思路和代码:
用的是基本的备忘录加上迭代的方法,先初始化1,2,3的值为0,1,2,然后用循环依次计算(i,n-i)的拆分的最大乘积,并且在计算出每个值之后将未存储的最大乘积存到cost数组当中。
integerBreak函数的执行步骤:
注:cost(x)表示x的最大分解乘积,cost为Hashmap类型。
初始化max
·n已经计算->输出cost中对应的值。
·n未计算过->max=i*n
->max取i * cost(n-i),cost(i) * cost(n-i),max中最大值
->将(n,max)键值对加入cost中。
代码
import java.util.HashMap;
import java.util.Map;
class Solution {
Map<Integer,Integer> cost = new HashMap<>();
void init(){
cost.put(1, 0);
cost.put(2, 1);
cost.put(3, 2);
}
public int integerBreak(int n) {
int max = 0;
if(n==0) {
return 0;
}
else if(n<=cost.size()) {
return cost.get(n);
}
for(int i=1;i<n;i++){
max = Math.max(max, i*(n-i));
int temp = integerBreak(n-i);
max = Math.max(max,Math.max(cost.get(i)*temp, i*temp));
}
cost.put(n, max);
return max;
}
}