题目:给你一根长度为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.
相信很多人对products数组的值有些疑问。
1、我的理解是这样的,如果你的length在0-3这个范围内是不需要products数组的,直接返回,如代码所示:
if (length < 2)
return 0;
if (length == 2)
return 1;
if (length == 3)
return 2;
2、只有当length长度大于等于4的时候才需要用到products数组,这也是为什么i从4开始。
另外再来解释一下为什么products[0]=0,products[1]=1,products[2]=2,products[3]=3,
我的理解是,当length=4时,那么products[4]=products[1]*products[3]或者products[4]=products[2]*products[2]。
所以由此,products[0]=0,products[1]=1,products[2]=2,products[3]=3。
不知道各位同学有没有理解,没写过几篇博客,大佬还请轻喷。
完整代码如下
public class CutRope {
public static void main(String[] args) {
CutRope rope = new CutRope();
System.out.println(rope.cutRope(8));
}
public int cutRope(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 = 0;
for (int i = 4; i <= length; i++) {
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;
}
}
以上