当前位置:网站首页>leetcode135. Distribute candy

leetcode135. Distribute candy

2022-07-07 08:38:00 No woman knocks the code in the heart, natural God!!

One : The analects of Confucius

 Insert picture description here

Two : subject

 Insert picture description here

3、 ... and : Upper code


class Solution {
    
public:
    int candy(vector<int>& ratings) {
    

    /**  Ideas :1. Here we traverse twice ( From left to right   From right to left ) 2. When we traverse from left to right   If the score on the right is higher than that on the left   Then count the candies of the children on the right   Add one to the candy number of the child on the left  3. When we traverse from right to left , If the score on the left is higher than that on the right   And the number of candies is less than that on the right   Then the number of sweets for the child on the left  =  The number of sweets of the child on the right +1 */

    map<int,int>m;
    map<int,int>:: iterator mt;
    int sum = 0;

    for(int i = 0; i < ratings.size(); i++) {
    
        m[i] = 1;
    }

    // From left to right 
    for(int i = 0; i < ratings.size()-1; i++) {
    
        if(ratings[i+1] > ratings[i]){
    // The number of candies of the children on the right is greater than the number of candies on the left 
            m[i+1] = m[i]+1;
        }
    }
    
    // From right to left 
    for(int i = ratings.size()-1; i > 0; i--) {
    
        if(ratings[i-1]  > ratings[i] && m[i-1] <= m[i]) {
    // m[i-1] <= m[i]  Make sure to add one side of the candy 
            m[i-1] = m[i] + 1;                           // The number of sweets is less than or equal to that on the right 
        } 
    }
   
    for(mt = m.begin(); mt != m.end(); mt++) {
    
        sum += mt->second;
    }

    // int sum = accumulate(mt->second().begin(),mt->second().end(),0);

    return sum;
    }
};
原网站

版权声明
本文为[No woman knocks the code in the heart, natural God!!]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130632286336.html