There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.
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.
Return the minimum number of candies you need to have to distribute the candies to the children.
Example 1:
Input: ratings = [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: ratings = [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.
Constraints:
n == ratings.length
1 <= n <= 2 * 104
0 <= ratings[i] <= 2 * 104
自己写的,最后一个用例超时了,时间复杂度On^2,最坏情况是每个rating都小于前一个rating
class Solution {
public:
int candy(vector<int>& ratings) {
//初始时每个candy都是1
//考察每个数右边的数,如果右边的rating比它大,右边candy加一
//如果右边的rating比它小,则自身和所有左边连续的更大的candy加一
vector<int> candys(ratings.size());
for(int i = 0; i < candys.size(); i++){
candys[i] = 1;
}
for(int i = 0; i < ratings.size() - 1; i++){
if(ratings[i+1] > ratings[i])
candys[i+1] = candys[i]+1;
else{//不管往前还是往后,相等的都不用去管
int j = i;
while(j >= 0 && candys[j] <= candys[j+1] && ratings[j] > ratings[j+1]){
candys[j] = candys[j+1]+1;
j--;
}
}
}
//上述循环也包含了最后一个,最后一个要么candy是1不用操作,要么比前一个rating大,在size-2的时候操作了
int res = 0;
for(int num : candys){
//cout << num ;
res += num;
}
return res;
//这题意思是只有rating涉及到连续的增减,candy才有连续的增减
}
};
书上答案,时间复杂度On,我真是傻逼
class Solution {
public:
int candy(vector<int>& ratings) {
vector<int> candys(ratings.size(),1);
for(int i = 0; i < ratings.size()-1;i++){
if(ratings[i+1] > ratings[i])
candys[i+1] = candys[i] + 1;
}
for(int i = ratings.size()-1; i >= 1; i--){
if(ratings[i-1] > ratings[i] && candys[i-1] <= candys[i]){
//if(ratings[i-1] > ratings[i]){
candys[i-1] = candys[i] + 1;
//candys[i-1] = max(candys[i]+1,candys[i-1]);
}
}
return accumulate(candys.begin(),candys.end(),0);
}
};