题目:
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?
思路: 扫描两遍数列,第一遍保证与左邻居有序,第二遍保证与右邻居有序。 时间复杂度O(N)
代码:
class Solution(object):
def candy(self, ratings):
if len(ratings) == 0:
return 0
candy = [0 for i in range(0,len(ratings))]
candy[0] = 1
for i in range(1,len(ratings)):
if ratings[i] > ratings[i-1]:
candy[i] = candy[i-1]+1
else:
candy[i] = 1
ans = candy[len(ratings)-1]
for i in range(len(ratings)-2,-1,-1):
if ratings[i] > ratings[i+1] and candy[i] <= candy[i+1]:
candy[i] = candy[i+1]+1
ans += candy[i]
return ans