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;
}
};
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;
}
};
相关文章推荐
- leetcode_Candy
- LeetCode:Candy
- 4.19 leetcode -19 candy
- LeetCode 135:candy 题解 Python
- leetcode:Candy
- 117_leetcode_Candy
- [LeetCode] Candy
- leetcode :Candy
- [LeetCode]Candy
- https://leetcode.com/problems/candy/
- Candy -- leetcode
- LeetCode:Candy
- LeetCode_Candy
- leetcode candy
- LeetCode139: Candy
- 【leetcode】Candy
- LeetCode-Candy-分糖果-逻辑关系
- Leetcode 135 Candy
- LeetCode || Candy
- [leetcode]Candy @ Python