【Sword Finger 14】Cut the rope

Cut the rope I

Greedy: time O(1), space O(1)

answer:

  1. In general, the more the rope is divided into segments, the larger the product will be
  2. In order to make the product larger, the more segments 3 are divided into, the larger the result will be
  3. If each section is 3 points long and the remaining length is 1, then divide the last section into 2 * 2> 1 * 3
class Solution {
    
    
public:
    int cuttingRope(int n) 
    {
    
    
        // 1.数学,贪心
        if (n < 4)
            return n - 1;
        int count = n / 3;
        int mod = n % 3;    // mod只能是0,1,2
        if (mod == 1)
        {
    
    
            mod = 4;
            count--;
        }
        else if (mod == 0)
            mod = 1;
        return pow(3, count) * mod;
    }
};

Cut the rope II:

Greedy + fast power: time O(logn), space O(1)

answer:

  1. The modulus condition is added on the basis of the previous question, that is, the result is very large, which may cause integer overflow
  2. The time complexity of conventional exponentiation is O(n), and the dichotomy exponentiation can reduce the time complexity to O(logn)
class Solution {
    
    
public:
    int mod = 1000000007;
    long long MY_POW(long long x, int n)
    {
    
    
        long long res = 1;
        while (n)
        {
    
    
            if (n & 1)  // 若n为奇数,则需要乘单独的x
            {
    
    
                res = res * x % mod;
            }
            // x^n = (x^2)^(n/2)
            x = x * x % mod;
            n /= 2;
        }
        return res;
    }
    int cuttingRope(int n) 
    {
    
    
        if (n < 4)
            return n - 1;
        int x = n / 3;
        int y = n % 3;  // y只有0,1,2三种取值
        if (y == 1)
            return MY_POW(3, x - 1) * 4 % mod;
        else if (y == 2)
            return MY_POW(3, x) * 2 % mod;
        else 
            return MY_POW(3, x);
    }
};

Guess you like

Origin blog.csdn.net/qq_45691748/article/details/112479498