Brushing notes (14)-cut the rope

Brushing notes (14)-cut the rope

Title description

Give you a rope of length n, please cut the rope into m lengths of integer length (m and n are integers, n> 1 and m> 1), the length of each rope is denoted as k [0], k [1], ..., k [m]. What is the maximum possible product of k [0] xk [1] x ... xk [m]? For example, when the length of the rope is 8, we cut it into three sections of length 2, 3, and 3, respectively, and the maximum product obtained at this time is 18.

Example 1

Input

copy

8

Output

copy

18

Idea: There is no limit to the number of splits in the question, and it seems intuitively irregular. 1,2,3,4 can directly get the results, and then consider the following

Because 4 can only be split into 1, 3 and 2, 2, obviously 2 * 2 is larger, so later encounter 4 can be directly split into 2, 2

5:1、2、2;2、3

6: 1, 5 (disassemble 5 as above); 2, 2, 2; 3 , 3 ;

7: 1,6 (6 then disassembled as above); 2,5 (then disassembled according to the above 5), 3.2.2 ;

......

Are split into 2, 3

If it is a multiple of three, all of them are directly split into three to get a certain power of three

If it is not a multiple of three, first split it into the multiple and remainder parts of three to get a power of three * remainder (2 or 1)

class Solution {
public:
    int cutRope(int number) {
        if(number==1)return 1;
        else if(number==2) return 1;
        else if(number==3)return 2;
        else if(number==4)return 4;
        else
        {
            if(number%3==0)
            {
                int x=number/3;
                return pow(3,x);
            }
            else
            {
                int x=number/3;
                int y=number%3;
                return pow(3,x)*y;
            }
        }
    }
};

 

Published 36 original articles · 19 praises · 20,000+ views

Guess you like

Origin blog.csdn.net/GJ_007/article/details/105470419