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)
糖果分配问题
本文介绍了一种高效的算法来解决糖果分配问题。该问题要求为不同评级的孩子分配糖果,并确保评级较高的孩子得到比邻居更多的糖果。通过两次遍历数组,首先从左到右确保递增的评级获得递增数量的糖果,然后从右到左调整以满足所有条件。
787

被折叠的 条评论
为什么被折叠?



