Sword refers to offer acwing 25 Cut the rope (mathematics)

Topic

Insert picture description here

answer

  1. This is a classic mathematical conclusion problem. Let’s talk about the conclusion first, that is, the length we cut is only 2 and 3, and 2 is at most 2. When the length of the rope modifies 3 and remains 1, the length of the rope is 2 2, and the rest Both are 3; when the modulo 3 is more than 2, one section is 2 and the rest are 3
  1. Proof: When a section of ai >=5, then we can split it into (ai-3) *3 = 3 *ai-9, we assume 3 *ai -9 >ai, then 2 *ai> 9 --- --> ai> 4.5 The hypothesis is true, and the length of each segment is not greater than 5 now
  1. Looking at the case of 4, for 4, we can split it into 2 * 2, all does not contain 4, because the contribution of 1 to the product is 0, so I will definitely not choose 1. Now each segment has only 2 3
  1. Assuming there are three 2s, then 2 * 2 *2 <3 * 3, so the length of 6 is cut into 3 * 3 is the optimal, so the number of 2 will not exceed 3.

Code

class Solution {
    
    
public:
    int maxProductAfterCutting(int n) {
    
    
        
        if(n<=3) return 1*(n-1);
        
        int res=1;
        if(n%3==1) res*=4 ,n-=4;
        if(n%3==2) res*=2, n-=2;
        while(n) res*=3,n-=3;
        
        return res;
        
    }
};

Guess you like

Origin blog.csdn.net/qq_44791484/article/details/114919216