Sword Finger Offer 14- I. Cut the Rope (C++) Greedy Algorithm

Here is 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). The length of each rope is k[0],k [1]...k[m-1]. What is the maximum possible product of k[0] k[1] …*k[m-1]? 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.

Example 1:

输入: 2
输出: 1
解释: 2 = 1 + 1, 1 × 1 = 1

Example 2:

输入: 10
输出: 36
解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36

prompt:

2 <= n <= 58
Note: This question is the same as the main website question 343: https://leetcode-cn.com/problems/integer-break/

Problem-solving ideas:

Mathematical derivation: a reasoning: the rope at equal length into multiple segments , the largest product obtained.
Corollary 2: When the rope is divided into multiple sections with a length of 3 as much as possible , the product is the largest.

Algorithm flow:

Insert picture description here
Insert picture description here

Complexity analysis:

Time complexity O(1) : only integer, remainder, and power operations.
Integer and remainder operations: The data mentions that integers that do not exceed the number of machines can be regarded as O(1)O;
exponentiation operations: refer to the information and mention that floating-point exponentiation is O(1).
Space complexity O(1) : Variables a and b use constant size extra space.

Author: jyd
link: https: //leetcode-cn.com/problems/jian-sheng-zi-lcof/solution/mian-shi-ti-14-i-jian-sheng-zi-tan-xin-si-xiang -by/
Source: LeetCode (LeetCode)
copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Find the pattern
Insert picture description here

class Solution {
    
    
public:
    int cuttingRope(int n) {
    
    
        if (n < 4)return n - 1;
        int a = n / 3, b = n % 3;
        if (b == 0)return a = pow(3, a);//pow(3, a)表示3的a次方
        if (b == 1)return a = pow(3, a-1) * 4;
        if (b == 2)return a = pow(3, a) * 2;
        return a;
    }
};

Author: z1m
link: https: //leetcode-cn.com/problems/jian-sheng-zi-lcof/solution/xiang-jie-bao-li-di-gui-ji-yi-hua-ji-zhu-dong -tai-/
Source: LeetCode (LeetCode)
copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/qq_30457077/article/details/114733448