给你一根长度为 n 的绳子,请把绳子剪成整数长度的 m 段(m、n都是整数,n>1并且m>1),每段绳子的长度记为 k[0],k[1]...k[m] 。请问 k[0]k[1]...*k[m] 可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。
class Solution {
public:
int cuttingRope(int n) {
vector<int> dp(n + 1);
dp[1] = 1;
for (int i = 2; i <= n; i++)
for (int j = 1; j < i; j++)
dp[i] = max(dp[i], max(dp[i - j] * j, (i - j) * j));
return dp[n];
}
};
math
class Solution {
public:
int cuttingRope(int n) {
if (n <= 3) return n - 1;
else if (n % 3 == 1)
return 4 * pow(3, (n - 4) / 3);
else if (n % 3 == 2)
return 2 * pow(3, (n - 2) / 3);
else return pow(3, n / 3);
}
};
or
class Solution {
public:
int cuttingRope(int n) {
if (n <= 3) return n - 1;
long res = 1;
while (n > 4) {
res = res * 3 % 1000000007;;
n -= 3;
}
return res * n % 1000000007;
}
};