For a rope with length i, we can cut by j and i - j, for every part, we can cut or not cut, so:
dp[i] = Max(dp[j], j) * Max(dp[i-j], i-j) for all j
class Solution {
public int cuttingRope(int n) {
int[] dp = new int[n + 1];
dp[1] = 1;
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= i / 2; j++) {
dp[i] = Math.max(dp[i], Math.max(j, dp[j]) * Math.max(i - j, dp[i - j]));
}
}
return dp[n];
}
}
Image what lengths will be left after cutting and get a maximum product:
= 5: not possible, cutting always have larger product
so, we need to get length 3 cut as much as possible when length > 4, because when 4, 2-2 cut will be better
class Solution {
public int cuttingRope(int n) {
if (n == 2) return 1;
if (n == 3) return 2;
long res = 1;
while (n > 4) {
res *= 3;
res %= 1000000007;
n -= 3;
}
return (int) (res * n % 1000000007);
}
}
class Solution {
private int mod = (int)1e9 + 7;
public int cuttingRope(int n) {
if(n < 4){
return n-1;
}
int cnt3 = n / 3;
if(n % 3 == 0){
return (int)pow(3, cnt3);
} else if(n % 3 == 1){
return (int)((pow(3, cnt3 - 1) * 4) % mod);
} else {
return (int)((pow(3, cnt3) * 2) % mod);
}
}
private long pow(long base, int num){
long res = 1;
while(num > 0){
if((num & 1) == 1){
res *= base;
res %= mod;
}
base *= base;
base %= mod;
num >>= 1;
}
return res;
}
}