给你一根长度为n的绳子,请把绳子剪成整数长的m段(m、n都是整数,n>1并且m>1,m<=n),每段绳子的长度记为k[1],…,k[m]。请问k[1]x…xk[m]可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。
输入描述:
输入一个数n,意义见题面。(2 <= n <= 60)
private static int cutRope(int target) {
int a = 0;
int c = 0;
int maxValue = 2;
if (target == 2) {
return 1;
}
if (target == 3) {
return 2;
}
if (target % 3 == 0) {
maxValue = (int)Math.pow(3, target / 3);
} else{
a = target - 2;
c = a % 3;
maxValue = maxValue * (int)Math.pow(3, a / 3);
if (0 != c) {
maxValue = maxValue * c;
}
}
return maxValue;
}
public class Solution {
int [] result = new int[61];
public int cutRope(int target) {
result[1] = 1;
result[2] = 2;
result[3] = 3;
if(target < 2){
return 0;
} else if(target == 2){
return 1;
} else if(target == 3){
return 2;
}
return getRope(target);
}
public int getRope(int n){
if(n == 1){
return 1;
}
if(n == 2) {
return 2;
}
int max = n - 1;
for(int i = 1; i < n ; i++){
int temp1 = result[i] == 0 ? getRope(i) : result[i];
int temp2 = result[n-i] == 0 ? getRope(n-i) : result[n-i];
if(temp1 * temp2 > max){
max = temp1 * temp2;
}
}
result[n] = max;
return max;
}
}