题目:给你一根长度为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。
思路:用动态规划算法,把大问题拆解为小问题
解决方案:
public class Question14 {
public static int maxProductAfterCutting_solution1(int length){
if (length < 2){
return 0;
}if (length == 2){
return 1;
}if (length == 3){
return 2;
}
int[] products = new int[length + 1];
products[0] = 0;
products[1] = 1;
products[2] = 2;
products[3] = 3;
int max;
for (int i=4; i<=length; i++){
max = 0;
for (int j=1; j<=i/2; j++){
int product = products[j] * products[i-j];
if (max < product){
max = product;
products[i] = max;
}
}
}
max = products[length];
return max;
}
public static void main(String[] args) {
System.out.println(maxProductAfterCutting_solution1(5));
}
}
思路:用贪婪算法。如果n>=5,则3(n-3)>=2(n-2);如果n=4,则22>13.
解决方案:
public class Question14 {
public static int maxProductAfterCutting_solution2(int length){
if (length < 2){
return 0;
}if (length == 2){
return 1;
}if (length == 3){
return 2;
}
// 尽可能多地剪去长度为3的绳子段
int timeOf3 = length / 3;
// 当绳子最后剩下的长度为4的时候,不能再剪去长度为3的绳子段
// 此时更好的方法是把绳子剪成长度为2的两段,因为2*2 > 3*1
if (length - timeOf3 * 3 == 1){
timeOf3 -= 1;
}
int timeOf2 = (length - timeOf3 * 3) / 2;
return (int)(pow(3, timeOf3))*(int)(pow(2,timeOf2));
}
public static void main(String[] args) {
System.out.println(maxProductAfterCutting_solution2(5));
}
}
网友评论