Original title address: https://oj.leetcode.com/problems/candy/
Test instructions
There is N children standing in a line. Each child is assigned a rating value.
You is giving candies to these children subjected to the following requirements:
- Each child must has at least one candy.
- Children with a higher rating get more candies than their neighbors.
What's the minimum candies you must give?
Problem-solving ideas: Ask for the most stingy candy distribution number. First scan the array from front to back, if the sequence increments, + 1, and then scan the array from back to front, sequence increment, +1. Ensure that the lowest (ratings minimum) is always 1.
Code: Time Complexity O (n), spatial complexity O (n)
classSolution:#@param ratings, a list of integers #@return An integer defCandy (self, ratings): Candynum= [1] *Len (ratings) forIinchRange (1, Len (ratings)):ifRATINGS[I-1] <Ratings[i]: candynum[i]= Candynum[i-1] + 1 forIinchRange (len (ratings)-2,-1, 1): ifRatings[i] > ratings[i + 1] andCandynum[i] <= Candynum[i + 1]: candynum[i]= Candynum[i + 1] + 1returnSUM (candynum)
[Leetcode] Candy @ Python