您的位置:首页 > 其它

【leetcode】Candy

2014-07-22 22:36 357 查看


Candy



链接:https://oj.leetcode.com/problems/candy/




描述:



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?



方法:


前后两遍扫描。注意题中没有提到如果相邻两个数相等的情况,从提交情况应该是相等归于小于一类。




代码如下:




int candy(vector<int> &ratings) {
int size = ratings.size();
if(size <= 0 ) return 0;
vector<int> candies(size, 1);
for(int i=1; i < size; ++i)
{
if(ratings[i] > ratings[i-1]){
candies[i] = candies[i-1] + 1;
}/*else if( ratings[i] == ratings[i -1])
{
candies[i] = candies[i - 1];
}*/
}

int result = candies[size - 1];

for(int i = size - 2; i >= 0; --i)
{
if( ratings[i] > ratings[i+1])
{
if( candies[i] < candies[i+1] + 1)
candies[i] = candies[i+1] + 1;
}/*else if( ratings[i] == ratings[i+1])
{
if( candies[i] < candies[i + 1])
candies[i] = candies[i+1];
}*/
result += candies[i];
}

return result;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: