leetcode+ 贪心,从左扫一遍,从右扫一遍

点击打开链接
class Solution {
public:
    int candy(vector& ratings) {
        int len = ratings.size();
        vector res(len);
        for(int i=1, inc =1; i ratings[i-1]){
                res[i] = max(inc++, res[i]);
            }
            else{
                inc = 1;
            }
        }
        for(int i=len-2, inc = 1; i>=0; i--){
            if(ratings[i] > ratings[i+1]){
                res[i] = max(inc++, res[i]);
            }
            else{
                inc = 1;
            }
        }
        return accumulate(res.begin(), res.end(), len);
    }
};

你可能感兴趣的:(Leetcode)