Leetcode 135. Candy
题目:
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?
思路:
这题本身可以用贪心法来做,我们用candy[n]表示每个孩子的糖果数,遍历过程中,如果孩子i+1的rate大于孩子i 的rate,那么当前最好的选择自然是:给孩子i+1的糖果数=给孩子i的糖果数+1
如果孩子i+1的rate小于等于孩子i 的rate咋整?这个时候就不大好办了,因为我们不知道当前最好的选择是给孩子i+1多少糖果。
解决方法是:暂时不处理这种情况。等数组遍历完了,我们再一次从尾到头遍历数组,这回逆过来贪心,就可以处理之前略过的孩子。
最后累加candy[n]即得到最小糖果数。
代码:
class Solution { public: int candy(vector<int>& ratings) { int num = ratings.size(); vector<int> res(num, 1); for(int i = 1; i < num; ++ i){ if(ratings[i] > ratings[i-1]) res[i] = res[i-1] + 1; } for(int i = num-1; i >0; --i){ if(ratings[i-1] > ratings[i]) res[i-1] = max(res[i]+1, res[i-1]); } int sum = 0; for(int i = 0; i < num; ++ i){ sum += res[i]; } return sum; } };