13.剪绳子

给你一根长度为 n 绳子,请把绳子剪成 m 段(m、n 都是整数,2≤n≤58 并且 m≥2)。

每段的绳子的长度记为 k[1]、k[2]、……、k[m]。

k[1]k[2]…k[m] 可能的最大乘积是多少?

例如当绳子的长度是 8 时,我们把它剪成长度分别为 2、3、3 的三段,此时得到最大的乘积 18。

样例:

输入:8
输出:18

代码:

class Solution {
    public int maxProductAfterCutting(int length)
    {
        //当绳子长度小于等于3时,直接返回最优解(剪成1和length-1)
        if(length<=3)return length-1;
        //初始化结果为1
        int res=1;
        //处理余数为1的情况:拆除一个4(即2+2,因为2*2 = 4 > 1*3 = 3)
        if(length%3==1){
            res = 4;
            length -= 4;
        //处理余数为2的情况:拆出一个2(因为2 > 1×1=1)
        }else if(length%3==2){
            res = 2;
            length -= 2;
        }
        //剩余长度全部拆成3的乘积(数学证明3的乘积最大)
        while(length>0){
            res *= 3;
            length -=3;
        }
        //返回结果
        return res;
    }
}
posted @ 2025-05-14 09:30  回忆、少年  阅读(17)  评论(0)    收藏  举报