LeetCode刷题实战135:分发糖果
共 1638字,需浏览 4分钟
·
2020-12-26 11:10
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?
题意
示例 1:
输入: [1,0,2]
输出: 5
解释: 你可以分别给这三个孩子分发 2、1、2 颗糖果。
示例 2:
输入: [1,2,2]
输出: 4
解释: 你可以分别给这三个孩子分发 1、2、1 颗糖果。
第三个孩子只得到 1 颗糖果,这已满足上述两个条件。
解题
思路:贪心算法
public class Solution {
public int candy(int[] ratings) {
int n = ratings.length;
int[] candies = new int[n];
for (int i = 0; i < n; i++) {
candies[i] = 1; //每人至少发一颗糖
}
for(int i = 1; i < n; i++){ //从前往后遍历ratings数组
if(ratings[i] > ratings[i - 1]){
candies[i] = candies[i - 1] + 1;
}
}
for(int i = n - 2; i >= 0; i--){ //从后往前遍历ratings数组
if(ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]){
candies[i] = candies[i + 1] + 1;
}
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum += candies[i];
}
return sum;
}
}