"Sword Finger Offer": the cut rope for brushing questions

"Sword Finger Offer": the cut rope for brushing questions

I don't know where I am going, but I am already on my way!
Time is hurried, although I have never met, but I met Yusi, it is really a great fate, thank you for your visit!
  • Topic :
    Give you a rope with a length of n. Please cut the rope into m segments of integer length (m and n are integers, n>1 and m>1, m<=n), and record the length of each rope Is k[1],...,k[m]. What is the maximum possible product of k[1]x...xk[m]? For example, when the length of the rope is 8, we cut it into three pieces with lengths of 2, 3, and 3. The maximum product obtained at this time is 18.
    Enter description: Enter a number n, see the title for the meaning. (2 <= n <= 60)
    Output description: output the answer.
  • Example :
示例 1 :
输入:8
返回值:18
  • Code 1:
# -*- coding:utf-8 -*-
class Solution:
    def cutRope(self, number):
        result = 1
        while number > 0:
            number = number -3
            if number == 1:
                result *= 4
                return result
            if number == 2:
                result *= 6
                return result
            result *= 3
        return result
  • Algorithm description:
    No matter how it is divided, the first cut of the rope will be divided into two segments, so it can be divided into sub-problems to solve;
    1 = 1;
    2 = 2;
    3 = 3;
    4 = 2 × 2;
    5 = 2 × 3;
    6 = 3 × 3;
    The numbers above 7 can be decomposed into the product of 2 and 3, and when the multiplier contains more 3s, the product is larger;
    therefore, just judge numberhow many threes there are, and proceed gradually -3Operation, know that the final is less than 3;
    if the remainder is 1, it means that before the -3operation is performed, number = 4the maximum product of 4 is still 4;
    if the remainder is 2, it means that before the -3operation is performed, number = 5the maximum product of 5 is 6;
    until the number <= 0end program.

Guess you like

Origin blog.csdn.net/qq_34331113/article/details/114998995