?LeetCode刷題實戰(zhàn)135:分發(fā)糖果
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
解釋: 你可以分別給這三個孩子分發(fā) 2、1、2 顆糖果。
示例?2:
輸入: [1,2,2]
輸出: 4
解釋: 你可以分別給這三個孩子分發(fā) 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; //每人至少發(fā)一顆糖
????????}
????????for(int?i = 1; i < n; i++){ //從前往后遍歷ratings數(shù)組
????????????if(ratings[i] > ratings[i - 1]){
????????????????candies[i] = candies[i - 1] + 1;
????????????}
????????}
????????for(int?i = n - 2; i >= 0; i--){ //從后往前遍歷ratings數(shù)組
????????????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;
????}
}
