135. Candy
题目大意
There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.
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.
Return the minimum number of candies you need to have to distribute the candies to the children.
中文释义
一排站着 n 个孩子。每个孩子都被分配了一个整数数组 ratings 中的评分值。
你需要给这些孩子分发糖果,但需遵守以下要求:
- 每个孩子至少分到一颗糖果。
- 评分更高的孩子比他们的邻居获得更多的糖果。
返回你需要拥有的最少糖果数量,以便将糖果分发给孩子们。
Example
Example 1:
- Input:
ratings = [1,0,2]
- Output:
5
- Explanation: 你可以分别给第一个、第二个和第三个孩子分发 2, 1, 2 颗糖果。
Example 2:
- Input:
ratings = [1,2,2]
- Output:
4
- Explanation: 你可以分别给第一个、第二个和第三个孩子分发 1, 2, 1 颗糖果。第三个孩子分到 1 颗糖果,因为它满足上述两个条件。
Constraints
n == ratings.length
1 <= n <= 2 * 10^4
0 <= ratings[i] <= 2 * 10^4
解题思路
算法描述
这段代码的目的是分配糖果给一排孩子,满足评分较高的孩子比其邻居获得更多的糖果。
-
首先初始化数组每个孩子获得糖果数为1。
-
从左至右遍历,判断当前孩子和左边的孩子相比,如果当前孩子评分更高,那么当