Leetcode|Difficulty|Two Dimensional Greedy|135. Distribute Candies (Forward Greedy + Backward Greedy)

Insert picture description here

1 Two-way greedy algorithm

Insert picture description here

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);
    }
};

Insert picture description here

Thanks

The picture comes from the "Code Random Record" public account, welcome everyone to pay attention to the official account

Guess you like

Origin blog.csdn.net/SL_World/article/details/114908032
Recommended