【LeetCode】135. Candy 分发糖果(Hard)(JAVA)
题目地址: https://leetcode.com/problems/candy/
题目描述:
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.
题目大意
老师想给孩子们分发糖果,有 N 个孩子站成了一条直线,老师会根据每个孩子的表现,预先给他们评分。
你需要按照以下要求,帮助老师给这些孩子分发糖果:
- 每个孩子至少分配到 1 个糖果。
- 相邻的孩子中,评分高的孩子必须获得更多的糖果。
那么这样下来,老师至少需要准备多少颗糖果呢?
解题方法
- 遍历两次,一次从左到右,一次从右到左,结果保存到一个一维数组里
- 先从左到右,如果当前元素大于前面的元素,前一个的结果 + 1,min[i] = min[i - 1] + 1
- 然后从右到左,如果当前元素大于前面的元素,前一个的结果 + 1, min[i + 1] + 1,然后和从左到右遍历的结果比较,取大的值
class Solution {
public int candy(int[] ratings) {
if (ratings.length <= 1) return ratings.length;
int[] min = new int[ratings.length];
for (int i = 0; i < ratings.length; i++) {
if (i == 0) {
min[i] = 1;
} else if (ratings[i] > ratings[i - 1]) {
min[i] = min[i - 1] + 1;
} else {
min[i] = 1;
}
}
int res = 0;
for (int i = ratings.length - 1; i >= 0; i--) {
if (i < ratings.length - 1 && ratings[i] > ratings[i + 1]) {
min[i] = Math.max(min[i], min[i + 1] + 1);
}
res += min[i];
}
return res;
}
}
执行耗时:3 ms,击败了77.77% 的Java用户
内存消耗:39.1 MB,击败了97.70% 的Java用户