1 Two-way greedy algorithm
Greedy strategy:
- Traverse from left to right, only compare cases where the right child’s score is greater than the left
- Traverse from right to left, only compare the cases where the left child’s score is greater than the right
class Solution {
public:
int candy(vector<int>& ratings) {
int size = ratings.size();
vector<int> num(size, 1);
// 1.前向贪心
for (int i = 1; i < size; i++)
if (ratings[i] > ratings[i-1])
num[i] = num[i-1] + 1;
// 2.后向贪心
for (int i = size - 2; i >= 0; i--)
if (ratings[i] > ratings[i+1])
// 第i个孩子也许比第i+1孩子拿到的糖果本来就多, 故用max
num[i] = max(num[i], num[i+1] + 1);
return accumulate(num.begin(), num.end(), 0);
}
};
Thanks
The picture comes from the "Code Random Record" public account, welcome everyone to pay attention to the official account