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?
Solution:Code:
<span style="font-size:14px;">class Solution {
public:
int candy(vector<int> &ratings) {
const int length = ratings.size();
if (length == 0 || length == 1) return length;
bool increase = true;
int increaseCount = 0, decreaseCount = 0, result = 0;
for (int i = 1; i < length; ++i)
if (ratings[i] > ratings[i-1]) {
if (increase) ++increaseCount;
else {
increase = true;
result += (increaseCount+1)*increaseCount/2+(decreaseCount+1)*decreaseCount/2-1+max(increaseCount, decreaseCount)+1;
increaseCount = 1;
decreaseCount = 0;
}
} else if (ratings[i] < ratings[i-1]) {
if (!increase) ++decreaseCount;
else {
increase = false;
decreaseCount = 1;
}
} else {
increase = true;
result += ((increaseCount+1)*increaseCount/2+(decreaseCount+1)*decreaseCount/2-1+max(increaseCount, decreaseCount)+1)+1;
increaseCount = 0;
decreaseCount = 0;
}
result += ((increaseCount+1)*increaseCount/2+(decreaseCount+1)*decreaseCount/2-1+max(increaseCount, decreaseCount)+1)+1;
return result;
}
};</span>