https://leetcode.com/problems/integer-break/
首先显然可以DP,要注意的就是n <= 3时直接返回,另外n > 3时,2、3位置的dp值为2和3(index本身)。
public class Solution {
public int integerBreak(int n) {
if (n <= 3) {
return n - 1;
}
int[] dp = new int[n + 1];
dp[1] = 1;
dp[2] = 2;
dp[3] = 3;
for (int i = 4; i <= n; i++) {
for (int j = 1; j <= i / 2; j++) {
dp[i] = Math.max(dp[i], dp[j] * dp[i - j]);
}
}
return dp[n];
}
}
最优解:
所有的数拆分之后的乘数在大于4的时候一定由3组成,小于等于4的时候则为它本身。
public class Solution {
public int integerBreak(int n) {
if (n <= 3) {
return n - 1;
}
int res = 1;
while (n > 4) {
res *= 3;
n -= 3;
}
return res * n;
}
}