題目描述
原題地址:https://leetcode-cn.com/problems/integer-break/
給定一個正整數 n,將其拆分為至少兩個正整數的和,并使這些整數的乘積最大化。 返回你可以獲得的最大乘積。
示例 1:
輸入: 2
輸出: 1
解釋: 2 = 1 + 1, 1 × 1 = 1。
示例 2:
輸入: 10
輸出: 36
解釋: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。
說明: 你可以假設 n 不小于 2 且不大于 58。
解法1——遞歸
遞歸的思路無非就是自頂向上,很容易想出來,代碼如下
//遞歸-自頂向下
public static int integerBreak(int n) {
return dfs(n);
}
public static int dfs(int n){
if(n == 1 || n == 2){
return 1;
}
int res = 0;
for(int i = 1;i < n;i++){
res = Math.max(res,Math.max(i * dfs(n - i),i * (n - i)));
}
return res;
}
這種方法雖然比較容易想出來,但是中間重復計算的非常多,實際在LeetCode中不能AC
。
解法2——動態規劃
動態規劃那么就是自底向上的方法,根據上一步的遞歸,狀態轉移方程為
其中,為區間
之間的數。
//動態規劃-自下向上
public static int integerBreak2(int n) {
int[] dp = new int[n + 1];
dp[2] = 1;
for(int i = 2;i <= n;i++){
for(int j = 1;j <= i - 1;j++){
dp[i] = Math.max(dp[i],Math.max(j * dp[i - j],j * (i - j)));
}
}
return dp[n];
}
解法3——數學分析
根據高中學習的均值不等式
,可以得到
設,那么目標積為
對上述函數求導數,可以得到
當時取得最大值,那么離
最近的兩個整數為
2
和3
,下面再來考慮時選擇3還是選擇2。
假設一個數,則乘積為
,對其兩邊取對數可以得到
由于,所以是
越大越好,所以應該盡可能的多取
3
.
//數學方法
public static int integerBreak3(int n){
if(n == 2){
return 1;
}
if(n == 3){
return 2;
}
int res = 1;
while(n > 4){
res *= 3;
n -= 3;
}
return res * n;
}