【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 <= 0) return 0;
int[] dp = new int[ratings.length];
dp[0] = 1;
for (int i = 1; i < dp.length; i++) {
if (ratings[i] > ratings[i - 1]) {
dp[i] = dp[i - 1] + 1;
} else {
dp[i] = 1;
}
}
int res = dp[dp.length - 1];
for (int i = dp.length - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1]) {
dp[i] = Math.max(dp[i + 1] + 1, dp[i]);
}
res += dp[i];
}
return res;
}
}
执行耗时:3 ms,击败了66.08% 的Java用户
内存消耗:39.5 MB,击败了66.45% 的Java用户
![](https://img-blog.csdnimg.cn/20201107174624800.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzE2OTI3ODUz,size_16,color_FFFFFF,t_70#pic_center)