Description
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:
1 | Input: [1,0,2] |
Example 2:
1 | Input: [1,2,2] |
解法
网上看到的思路:先从左往右扫描一遍, 如果后面一个比前面大, 那么他分配的就多一颗糖, 否则就是1. 但是这样会产生一种情况, 就是两个相邻的排名一样, 那么后一个还是分一个, 但是后面的可能比这个值小, 但是仍然分得和这个值一样的糖, 因此还要从右往左再扫描一遍来补偿小的值.
具体代码如下:
1 | class Solution { |