To prove safety offer face questions 14 (java version): cut the rope

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/littlehaes/article/details/91411165

welcome to my blog

To prove safety offer face questions 14 (java version): cut the rope

Title Description

You n having a length of rope, the rope please cut segment m (m, n are integers, n> 1, m> 1 ), the length of each rope is referred to as k [0], k [1 ] , ..., k [m]. Will k [0] * k [1 ] * ... k [m] is the product of the largest possible number?
For example, when the length of the rope is 8:00, we cut it into lengths of 2 , three sections 3,3, the product obtained at that time is maximum 18

Thinking

  • Dynamic programming: Note sub-sub-sub-problems and relationship issues, such as: We cut the length of the rope 3 or 1,2 2,1 two kinds, regardless of 1,1,1 this case, that is only cut once

Dynamic programming problem solving features

  • Optimal solution seeking a problem
  • The whole question of the optimal solution depends on the individual sub-optimal solutions
  • The big problem is decomposed into several small problems, there are problems between these small smaller overlapping subproblems
  • From the analysis of the problem down to solve the problem from the bottom up

the complexity

Time complexity: O (n ^ 2)
space complexity: O (n)

    public static int maxProductAfterCutting_solution(int length){
        if(length < 2) // 长度小于2没法切. 长度为1的绳子没法切;但是某个绳子切完后可以包含长为1的绳子,注意这二者的区分
            return 0;
        if(length==2)
            return 1;
        if(length==3)
            return 2;
        // products的索引为1,2,3时只是表示绳子长度为1,2,3
        // products的索引i大于3时,表示长为i的绳子剪切后各段乘积能得到的最大值
        int[] products = new int[length+1]; // 长度加一后,最后一个索引是length, 方便表示
        products[1] = 1;
        products[2] = 2;
        products[3] = 3;
        for(int i=4; i<=length; i++){
            // for(int j=1; j<=i-1; j++){ //长为i的绳子,切割位置可以是{1,2,3,...i-1}
            for(int j=1; j<=i/2; j++){ // 长为3的绳子,可以切成1,2; 2,1; 效果是一样的,所以只用切i/2次就行    // 可能要问不是还能切成1,1,1这种吗? 为什么只切1次? 1,1,1这种情况在1,2中已经考虑过了,1,1是2的两个子问题. 这里要明确子问题与更小的子问题的关系
                if(products[i] < products[j]*products[i-j])
                    products[i] = products[j]*products[i-j];
            }
        }
        return products[length];
    }

Guess you like

Origin blog.csdn.net/littlehaes/article/details/91411165