My simplest solution


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

  • 0
    A

    Inspired by yours. Here's my python solution

    def candy(self, ratings):
        size = len(ratings)
        Candy = [1] * size
        
        for i in xrange(1, size):
            if ratings[i] > ratings[i-1]:
                Candy[i] = Candy[i-1]+1
                
        # from size-2 to 0
        for i in xrange(size-2, -1, -1):
            if ratings[i] > ratings[i+1]:
                Candy[i] = max(Candy[i], Candy[i+1] + 1)
                
        return sum(Candy)

Log in to reply
 

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