美文网首页
面试题14:剪绳子

面试题14:剪绳子

作者: scott_alpha | 来源:发表于2019-10-05 23:18 被阅读0次

题目:给你一根长度为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。
思路:用动态规划算法,把大问题拆解为小问题
解决方案:

public class Question14 {
    public static int maxProductAfterCutting_solution1(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;
        for (int i=4; i<=length; i++){
            max = 0;
            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;
    }

    public static void main(String[] args) {
        System.out.println(maxProductAfterCutting_solution1(5));
    }
}

思路:用贪婪算法。如果n>=5,则3(n-3)>=2(n-2);如果n=4,则22>13.
解决方案:

public class Question14 {
 public static int maxProductAfterCutting_solution2(int length){
        if (length < 2){
            return 0;
        }if (length == 2){
            return 1;
        }if (length == 3){
            return 2;
        }

        // 尽可能多地剪去长度为3的绳子段
        int timeOf3 = length / 3;
        // 当绳子最后剩下的长度为4的时候,不能再剪去长度为3的绳子段
        // 此时更好的方法是把绳子剪成长度为2的两段,因为2*2 > 3*1
        if (length - timeOf3 * 3 == 1){
            timeOf3 -= 1;
        }
        int timeOf2 = (length - timeOf3 * 3) / 2;
        return (int)(pow(3, timeOf3))*(int)(pow(2,timeOf2));
    }

    public static void main(String[] args) {
        System.out.println(maxProductAfterCutting_solution2(5));
    }
}

相关文章

  • 剪绳子

    《剑指offer》面试题14:剪绳子 题目:给你一根长度为n的绳子,请把绳子剪成m段 (m和n都是整数,n>1并且...

  • 面试题14:剪绳子

    给你一根长度为 n 的绳子,请把绳子剪成 m 段(m、n 都是整数,并且)。每段的绳子的长度记为、、……、。可能的...

  • 面试题14:剪绳子

    牛客上面没有这道题,自己做,书上再解释的时候,没有很详细的解释代码初始化部分,想了好久。

  • 面试题14:剪绳子

    前序动态规划与贪婪算法如果面试题是求一个问题的最优解(通常是最大值和最小值),而且该问题可以分解为若干个子问题,并...

  • 面试题14: 剪绳子

  • 面试题14:剪绳子

    题目:给你一根长度为n的绳子,请把绳子剪成m段(m、n都是整数,n>1并且m>1),每段绳子的长度即为k[0],k...

  • 面试题14:剪绳子

    题目 给你一根长度为n的绳子,请把绳子剪成m段(m,n都是整数,n>1且m>1)。每段绳子的长度记为k[0],k[...

  • 面试题14:剪绳子

    题目 :给你一根长度为n的绳子,请把绳子剪成整数长的m段(m、n都是整数,n>1并且m>1),每段绳子的长度记为k...

  • 剑指offer第二版-14.剪绳子(动态规划)

    本系列导航:剑指offer(第二版)java实现导航帖 面试题14:剪绳子 题目要求:给你一根长度为n的绳子,请把...

  • 14 剪绳子

    注:1到3是特殊情况

网友评论

      本文标题:面试题14:剪绳子

      本文链接:https://www.haomeiwen.com/subject/pfiypctx.html