Python two pass solution


  • 2
    G

    First, make sure I have right number of candy when compared to my left kid.
    Then, make sure I have the right number of candy when compared to my right kid.

    class Solution:
        # @param ratings, a list of integer
        # @return an integer
        # 5:46
        def candy(self, ratings):
            if not ratings:
                return 0
    
            n = len(ratings)
            candy = [1] * n
            for i in range(1, n):
                if ratings[i] > ratings[i - 1]:
                    candy[i] = candy[i - 1] + 1
                
            for i in range(n - 2, -1, -1):
                if ratings[i] > ratings[i + 1] and candy[i] <= candy[i + 1]:
                    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.