您的位置:首页 > 其它

leetcode之Candy

2014-12-06 14:57 281 查看
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?

问题链接

cpp代码如下:

class Solution {
public:
int candy(vector<int> &ratings) {
int s=ratings.size();
if(s==0)return 0;
vector<int> tmp;
tmp.resize(s);
tmp[0]=1;
for(int i=1;i<s;++i){
if(ratings[i]>ratings[i-1])tmp[i]=tmp[i-1]+1;
else tmp[i]=1;
}
int ans=tmp[s-1];
tmp[s-1]=1;
for(int i=s-2;i>=0;--i){
if(ratings[i]>ratings[i+1]){
int t=tmp[i+1]+1;
ans+=t>tmp[i]?t:tmp[i];
tmp[i]=t;
}else{
ans+=tmp[i];
tmp[i]=1;
}
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: