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?
翻译:
多个小朋友站成一排,根据他们的得分分发糖果,得分高的小朋友要比旁边得分低的小朋友得到的糖果多,每个小朋友至少得到一枚糖果,问最少要准备多少糖果?
思路:
先从左到右扫描一遍,使得右边比左边得分高的小朋友糖果数比左边多。
再从右到左扫描一遍,使得左边比右边得分高的小朋友糖果数比右边多。
class Solution {
public:
int candy(vector<int> &ratings) {
int n = ratings.size();
if(n == 0)return -1;
if(n == 1)return 1;
vector<int> candy(n,1);
for(int i=1;i<n;i++)
candy[i] = ratings[i]>ratings[i-1]?candy[i-1]+1:1;
for(int i=n-2;i>=0;i--)
if(ratings[i]>ratings[i+1]&&candy[i]<=candy[i+1])
candy[i] = candy[i+1]+1;
return accumulate(candy.begin(),candy.end(),0);
}
};