Problem:
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
- Each child must have at least one candy.
- Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
Solution:
只能说这个方法太巧了
class Solution(object):
def candy(self, ratings):
"""
:type ratings: List[int]
:rtype: int
"""
candies=[1 for i in range(len(ratings))]
for i in range(len(ratings)-1):
if ratings[i+1]>ratings[i]:
candies[i+1]=candies[i]+1
for i in range(len(ratings)-1,0,-1):
if ratings[i-1]>ratings[i]:
candies[i-1]=max(candies[i-1],candies[i]+1)
return sum(candies)