25.07.2021
小白一枚,文章仅当日记本记录学习进度 ;)
如被浏览,请多多指教,非常感谢大家纠错与建议!
(因留学顺便练习英语,所以部分用英文笔记,并无他意)
Solution - Greedy algorithm (Java)
We can use the greedy algorithm strategy to solve this problem by only considering the relationship of neighbors.
1. Initializing one candy for every child in the array
2. 1st Iteration: from left to right, give one more candy than the left one if the right one is bigger
3. 2nd Iteration: from right to left, since the array was already iterated once, so during this iteration, we will have to compare the number of candies this child got after the 1st iteration with those he got after the 2nd iteration, and keep the maximum number.
class Solution {
public int candy(int[] ratings) {
int size = ratings.length;
if (size < 2) return size;
int[] res = new int[size];
for (int i = 1; i < size; i++) {
if (ratings[i] > ratings[i-1]) {
res[i] = res[i-1] + 1;
}
}
for (int i = size - 1; i > 0; i--) {
if (ratings[i] < ratings[i-1]) {
res[i-1] = Math.max(res[i-1], res[i] + 1);
}
}
int sum = 0;
for (int value : res) {
sum += value;
}
return ratings.length + sum; // ratings.length相当于每人一颗糖的总数
}
}