Sharing my 40ms C++ solution


  • 1
    T
    class Solution {
    public:
        int candy(vector<int>& ratings) {
            int n = ratings.size();
            if(n<=1)
                return n;
                
            vector<int> candies(n, 1);
            int i;
            
            for(i=1; i<n; i++)
            {
                if(ratings[i]>ratings[i-1] && candies[i]<=candies[i-1])
                    candies[i] = candies[i-1]+1;
            }
            
            for(i=n-2; i>=0; i--)
            {
                if(ratings[i]>ratings[i+1] && candies[i]<=candies[i+1])
                    candies[i] = candies[i+1]+1;
            }
            
            int result = 0;
            for(i=0; i<n; i++)
                result += candies[i];
                
            return result;
        }
    };

Log in to reply
 

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