135. Candy
Difficulty: Hard
Topics: Greedy
Similar Questions:
Problem:
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?
Example 1:
Input: [1,0,2] Output: 5 Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
Example 2:
Input: [1,2,2] Output: 4 Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions.
Solutions:
class Solution {
public:
int candy(vector<int>& ratings) { // pay attention to the condition that two adjecent ratings are equal
int n = ratings.size();
vector<int> candyCount (n, 0);
vector<pair<int, int>> ratingWithIndex;
for (int i = 0; i < n; ++i) {
ratingWithIndex.push_back({ratings[i], i});
}
sort(ratingWithIndex.begin(), ratingWithIndex.end());
int sum = 0;
for (int i = 0; i < n; ++i) {
int index = ratingWithIndex[i].second;
candyCount[index] = 1;
if (index - 1 >= 0 && ratings[index] > ratings[index - 1]) {
candyCount[index] = max(candyCount[index], candyCount[index - 1] + 1);
}
if (index + 1 < n && ratings[index] > ratings[index + 1]) {
candyCount[index] = max(candyCount[index], candyCount[index + 1] + 1);
}
sum += candyCount[index];
}
return sum;
}
};