c++ solution (26ms beats 100%)


  • 0
    C
    class Solution {
    public:
        int candy(vector<int>& ratings) {
            int len=ratings.size();
            vector<int>ans(len,1);
            for(int i=0;i<len-1;i++){
                if(ratings[i]<ratings[i+1]){
                    ans[i+1]=ans[i]+1;
                }
            }
            for(int i=len-1;i>0;i--){
                if(ratings[i]<ratings[i-1]&&ans[i-1]<=ans[i]){
                    ans[i-1]=ans[i]+1;
                }
            }
            int sum=0;
            for(int i=0;i<len;i++)sum+=ans[i];
            return sum;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.