您的位置:首页 > 其它

[Leetcode] 135. Candy

2017-05-12 21:19 337 查看
题目:

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: