题目描述
给你一根长度为n的绳子,请把绳子剪成m段(m、n都是整数,n>1并且m>1),每段绳子的长度记为k[0],k[1],…,k[m]。请问k[0]xk[1]x…xk[m]可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。
解题思路:把绳子对半折相乘取得的值往往是最大的,所以先对绳子对半折(9对半折取得 4 和 5),但是把子绳子相乘却不一定是最大的,如9剪为 4 2 3(5剪为2 3 )相乘值为24 ,而9剪为3 6时,乘积小于4 *5=20,但6减为3 3,则3x3x3=27
大于24;所以计算时还要考虑距离对半折最近的一种折法。
int a1=target/2;//对半折
int a2=target-a1;
int b1=target/2-1;//对半折最近的一种折法
int b2=target-b1;
第一次折完后,继续对其子绳折,其实就是一种递归的方法,具体代码如下
class Solution {
public int cutRope(int target) {
if(target==3)
return 2;
if(target==4)
return 4;
if(target==2)//直接返回的情况
return 1;
int a1=target/2;
int a2=target-a1;
int b1=target/2-1;
int b2=target-b1;
return Math.max(cutRope1(a1)*cutRope1(a2),cutRope1(b1)*cutRope1(b2));
}
public int cutRope1(int target) {
if(target==3)//当子绳子长度为 1 2 3 4 时,无需在折,直接返回
return 3;
if(target==4)
return 4;
if(target==2)
return 2;
if(target==1)
return 1;
int a1=target/2;
int a2=target-a1;
int b1=target/2-1;
int b2=target-b1;
//返回折法中的乘积最大值
return Math.max(cutRope1(a1)*cutRope1(a2),cutRope1(b1)*cutRope1(b2));
}
}