您的位置:首页 > 编程语言 > Python开发

【LeetCode 135】Candy (Python)

2018-03-17 15:22 746 查看

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