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?
Example 1:
Input: [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
Example 2:
Input: [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.
LeetCode:链接
初始化所有孩子糖果为1颗,接下来从左到右扫描进行“修正”。
假设我们只考虑左边孩子的情况,如果当前孩子大于左边孩子,那么糖果要在左边孩子基础上+1.
这样扫描一遍以后,我们可以保证,对于任意的 i > 0 有 ans[i]>ans[i-1] ( if ratings[i] >rating[i-1])
接下来从右向左扫描,如果当前孩子大于右边的孩子,并且糖果数少于右边的,要在右边的孩子基础上+1
总结如下:第一次扫描保证了每个比左边高分的孩子比左边的糖果多,第二次则是右边。
class Solution(object):
def candy(self, ratings):
"""
:type ratings: List[int]
:rtype: int
"""
if len(ratings) <= 1:
return len(ratings)
n = len(ratings)
ans = [1] * n
for i in range(1, n):
if ratings[i] > ratings[i-1]:
ans[i] = ans[i-1] + 1
for i in range(n-2, -1, -1):
if ratings[i] > ratings[i+1] and ans[i] <= ans[i+1]:
ans[i] = ans[i+1] + 1
return sum(ans)