[Leetcode] 135. Candy

来源:互联网 发布:电商系统源码下载 编辑:程序博客网 时间:2024/06/18 09:40

题目:

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


0 0
原创粉丝点击