343. Integer Break - cocoder39/coco39_LC GitHub Wiki
Method 1: math
7 = 3 + 3 + 1; 8 = 3 + 3 + 2; ...
int integerBreak(int n) {
if (n == 2) return 1;
if (n == 3) return 2;
if (n == 4) return 4;
int res = 1;
while (n > 4) {
res *= 3;
n -= 3;
}
return res * n;
}
Method 2 DP:
product[i] is max product if i is broken into more than one int, i is max product if i is broken into one product. Hence product[i] = max(k, product[k]) * (i - k)
. sometimes k
is greater than product[k]
eg. k = 2
public int integerBreak(int n) {
int dp[] = new int[n+1];
dp[1] = 1;
for (int i = 2; i <= n; i++) {
for (int j = 1; j < i; j++) {
dp[i] = Math.max(dp[i], Math.max(j, dp[j]) * Math.max(i-j, dp[i-j]));
}
}
return dp[n];
}