Stay Hungry,Stay Foolish!

135. 分发糖果

135. 分发糖果

https://leetcode.cn/problems/candy/description/?envType=study-plan-v2&envId=top-interview-150

 

Code

class Solution {
public:
    int candy(vector<int>& ratings) {
        int n = ratings.size();

        vector<int> left(n, 0);
        vector<int> right(n, 0);

        /*
        walk from left to right,
        if current rating increase than previous one, 
        then the current sweets should be one more than previous one,
        otherwise, the current sweet should be one
        */
        left[0] = 1;
        for(int i=1; i<n; i++){
            if (ratings[i] > ratings[i-1]){
                left[i] = left[i-1] + 1;
            } else {
                left[i] = 1;
            }
        }

        /*
        walk from right to left,
        if current rating increase than previous one, 
        then the current sweets should be one more than previous one,
        otherwise, the current sweet should be one
        */
        right[n-1] = 1;
        for(int i=n-2; i>=0; i--){
            if (ratings[i] > ratings[i+1]){
                right[i] = right[i+1] + 1;
            } else {
                right[i] = 1;
            }
        }

        /*
        for each positon, 
        the deserved sweets should be met by rule:
        greater than left and greater than right
        */
        int ans = 0;
        for(int i=0; i<n; i++){
            ans += max(left[i], right[i]);
        }

        return ans;
    }
};

 

posted @ 2024-04-19 09:15  lightsong  阅读(2)  评论(0编辑  收藏  举报
Life Is Short, We Need Ship To Travel