时间限制:1秒 空间限制:32768K
题目描述
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 neighbours.
What is the minimum candies you must give?
我的代码
class Solution {
public:
int candy(vector<int> &ratings) {
int n=ratings.size();
if(n<1)
return 0;
if(n==1)
return 1;
vector<int> num(n,1);
for(int i=1;i<n;i++)
if(ratings[i]>ratings[i-1])
num[i]=num[i-1]+1;//从左到右保证题目要求
for(int i=n-2;i>=0;i--)
if((ratings[i]>ratings[i+1])&&(num[i]<=num[i+1]))
num[i]=num[i+1]+1;//从右到左保证题目要求
int res=0;
for(int i=0;i<n;i++)
res+=num[i];
return res;
}
};
运行时间:22ms
占用内存:692k