一、问题描述
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?
二、问题分析初始化每个孩子一个糖果;
从左往右扫描,保证每个rating高的孩子比其左邻居孩子糖果多;
从右往左扫描,保证每个rating高的孩子比其右邻居孩子糖果多,这时必须要做max操作。
例如具体取值为rating = {4,2,3,4,1}
初始化复制后的candy = {1,1,1,1,1}
从左往右扫描后candy = {1,1,2,3,1}
从左往右扫描后candy = {2,1,2,4,1},标红的数值必须做max操作。
三、算法代码
public class Solution {
public int candy(int[] ratings) {
int [] candy = new int [ratings.length];
//每个至少一个糖果
for(int i = 0; i <= candy.length - 1; i++){
candy[i] = 1;
}
//从左往右扫描,保证每个rating高的孩子比其左邻居孩子糖果多
for(int i = 1; i <= ratings.length - 1; i++){
if(ratings[i] > ratings[i - 1]){
candy[i] = candy[i - 1] + 1;
}
}
//从右往左扫描,保证每个rating高的孩子比其右邻居孩子糖果多
for(int i = ratings.length - 2; i >= 0; i--){
if(ratings[i] > ratings[i + 1]){
//这里必须做max操作,例如ratings情形4,2,3,4,1的倒数第二个ratings 4糖果赋值情形。
candy[i] = Math.max(candy[i], candy[i + 1] + 1);
}
}
//计算最后的糖果数
int result = 0;
for(int i = 0; i <= ratings.length - 1; i++){
result += candy[i];
}
return result;
}
}