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

[Leetcode]Candy

2015-02-03 13:33 267 查看
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?

进行两次扫描,第一次扫描的时候从左往右,维护对于每一个小孩左边所需要最少的糖果数量,存入数组num中,第二次扫描从右往左扫,维护右边所需的最少糖果数,并且比较将左边和右边大的糖果数量存入结果数组对应元素中,然后将糖果数累加~时间复杂度为O(n)~两边扫描的方法是一种比较常用的技巧,当遇到变量跟左右元素有关系的题目时可以尝试用这种解法

class Solution:
# @param ratings, a list of integer
# @return an integer
def candy(self, ratings):
if ratings is None or len(ratings) == 0:
return 0
num = [0] * len(ratings)
num[0] = 1
for i in xrange(1, len(ratings)):
if ratings[i] > ratings[i - 1]:
num[i] = num[i - 1] + 1
else:
num[i] = 1
res = num[-1]
for i in xrange(len(ratings) - 2, -1, -1):
cur = 1
if ratings[i] > ratings[i + 1]:
cur = num[i + 1] + 1
num[i] = max(num[i], cur)
res += num[i]
return res
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode python