剑指offer 面试题14:剪绳子 java

Github 源码地址

题目:

给你一根长度为n的绳子,请把绳子剪成m段,记每段绳子长度为k[0],
k[1]...k[m-1],求k[0]k[1]...k[m-1]的最大值。已知绳子长度n为整数
,m>1(至少要剪一刀,不能不剪),k[0],k[1]...k[m-1]均要求为整数。
例如,绳子长度为8时,把它剪成3-3-2,得到最大乘积18;绳子长度
为3时,把它剪成2-1,得到最大乘积2。

动态规划解法:

public class MaxProductAfterCutting {
    public static void main(String args[]) {
        int cutting = getMaxProductAfterCutting(3);
        System.out.println(cutting);
    }

    private static int getMaxProductAfterCutting(int len) {
        int max = 0;
        if (len < 2)
            return 0;
        if (len == 2)
            return 1;
        if (len == 3)
            return 2;
        //存储长度从 0-len 的最大结果
        int[] products = new int[len + 1];// 将最优解存储在数组中
        // 数组中第i个元素表示把长度为i的绳子剪成若干段之后的乘积的最大值
        products[0] = 0;
        products[1] = 1;
        products[2] = 2;
        products[3] = 3;
        //自底向上开始求解
        for (int i = 4; i <= len; i++) { //i表示长度
            for (int j = 1; j <= len / 2; j++) {//由于长度i存在(1,i-1)和(i-1,1)的重复,所以只需要考虑前一种
                int product = products[j] * products[i - j];
                if (max < product)
                    max = product;
            }
            products[i] = max;
        }
        max = products[len];
        return max;
    }
}

贪心算法

public static int maxProductWithGreedy(int len) {
        if (len < 2)
            return 0;
        if (len == 2)
            return 1;
        if (len == 3)
            return 2;
        //啥也不管,先尽可能减去长度为3的段
        int timeOfThree = len / 3;

        //判断还剩下多少,再进行处理
        if (len - timeOfThree * 3 == 1)
            timeOfThree -= 1;
        int timeOfTwo = (len - timeOfThree * 3) / 2;

        return (int) ((Math.pow(3, timeOfThree)) * (Math.pow(2, timeOfTwo)));
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值