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?
题目源地址:https://oj.leetcode.com/problems/candy/
题目大概意思如下:给一群小孩子发糖,每个小孩子分配了一个值,对每个小孩子来说, 至少有一颗糖,并且如果他的值比他挨着的小孩子的值要高,他所分得的糖也要多,求所需要的最少糖的数量。
题目提示了用贪心算法。
思路如下:
(1)定义一个数组,大小和孩子数量一样, 初始值都是1(因为每个孩子至少有一颗糖)。
(2)从第二值开始到尾遍历, 如果比前一个值大, 数组对应的值加1。
(3)从尾到头再进行一次第二步的过程, 有一点需要注意, 因为第二步之后可能满足了条件, 所以加1之前判断下是否破坏了值大糖多的条件。
python代码如下:
class Solution:
# @param ratings, a list of integer
# @return an integer
def candy(self, ratings):
if ratings == None:
return 0
size = len(ratings)
if size == 0:
return 0
if size == 1:
return 1
assign_count = [1] * size
for i in range(1, size):
if ratings[i] > ratings[i - 1]:
assign_count[i] = assign_count[i-1] + 1
for i in range(size-2, -1, -1):
if ratings[i] > ratings[i+1] and \
assign_count[i] <= assign_count[i+1]:
assign_count[i] = assign_count[i+1] + 1
return sum(assign_count)