Offer face questions prove safety cut the rope 14

Question: you a string of length n, please cut the rope segment length integer m (m, n are integers, n> 1 and m> 1), the length of each rope is referred to as k [0] , k [1], ..., k [m]. Will k [0] xk [1] x ... xk [m] maximum possible product is how much? For example, when the length of the rope is 8:00, we cut it into lengths of three sections 2,3,3 of the product obtained at this time is the maximum 18.

Input: length n

Output: maximum product rope segment

Ideas:

Dynamic Programming

Defined function f (n) is the maximum segment length to the length of the product is cut into segments n rope f(n)=max(f(i)*f(n-i)), i=1...n/2, sub-optimal solution of the original problem of optimal solutions may be composed.

Between the sub-sub-problem and the problem of overlapping, and therefore the bottom-up method (open array storing sub-optimal solution of the problem) is calculated from f (2), f (3), f (4) ... f (n), the output of f (n).

Special case: Because the number of segments is greater than 1, so the length of the rope when the result is 2, 3, respectively 1 and 2.

greedy

Greedy strategy:

When n> = 5, as the length of the rope 3 is cut, when the remaining length of the rope 4, is cut into two lengths of rope 2.

Prove optimal solution:

When n> = 5, 3 * ( n-3)> n, 2 * (n-2)> n and 3 * (n-3)> = 2 * (n-2) \RightarrowWhen the length of rope is greater than the rest of the It is equal to 5, as cut length of 3.

When n is 4, cut length of cord 2 causes the product of the maximum section 2.

Code:

Dynamic Programming

class Solution {
public:
    int cutRope(int number) {
        if(number<2)
            return 0;
        if(number==2)
            return 1;
        if(number==3)
            return 2;
        int* result=new int[number+1];
        result[0]=0;
        result[1]=1;
        result[2]=2;
        result[3]=3;
        int max=0;
        for(int i=4;i<=number;++i)
        {
            for(int j=1;j<=i/2;++j)
            {
                int temp=result[j]*result[i-j];
                if(temp>max)
                    max=temp;
            }
            result[i]=max;
        }
        max=result[number];
        delete[] result;
        return max;
    }
};

greedy

int cutRope(int number) {
        if(number<2)
            return 0;
        if(number==2)
            return 1;
        if(number==3)
            return 2;
        int result;
        int timesOf3=number/3;
        if(number-3*timesOf3==1)
        {
            --timesOf3;
            return pow(3,timesOf3)*4;
        }
        return pow(3,timesOf3)*(number-3*timesOf3);
    }

Complexity analysis:

Dynamic programming algorithm: time complexity O (n ^ 2), space complexity O (n)

Greedy algorithm: time complexity of O (1), the space complexity of O (1)

Published 56 original articles · won praise 10 · views 6796

Guess you like

Origin blog.csdn.net/qq_22148493/article/details/104445169