offer/src/Question14.java

38 lines
1.2 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 剪绳子,绳子长度乘积最大
*/
public class Question14 {
public static void main(String[] args) {
int length = 8;
int result = cutMaxRopeType(length);
System.out.println(result);
}
private static int cutMaxRopeType(int length) {
//当绳子长度小于4时因为必须要剪一次实际不剪断的值已经最大返回固定计算值。
if (length < 2) {
return 0;
}
if (length == 2) {
return 1;
}
if (length == 3) {
return 2;
}
/**
* 当绳子长度大于等于5时可知3(n-3) > 2(n-2)
* 所以要把绳子尽量剪成长度为3的段不够3时剪成长度为2的段
* 如果把绳子分为大于3的段比如5=2*3所以最终还是比较剪成2段和3段的大小
*/
int cut3Frequency = length / 3;
//此时分出一个3剪成2*2
if (length - cut3Frequency * 3 == 1){
cut3Frequency --;
}
//剪成2段的次数
int cut2Frequency = (length - cut3Frequency * 3) / 2;
int result = (int) (Math.pow(3, cut3Frequency) * Math.pow(2, cut2Frequency));
return result;
}
}