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.
思路1:
贪心,右侧比左侧大的时候,直接+1,但是需要处理的是右侧比左侧小的时候,因此,需要额外第二遍从右往左的遍历,用来调整,然后两个求和即可
时间复杂度:O(n)
空间复杂度O(n)
思路2:
如果是非递减,很简单,如果出现递减了,需要关键处理的部分。
可以通过补偿的方法,也即,如果出现递减,则前面每个需要一个修正值。
时间复杂度:O(n)
空间复杂度:O(1)