您的位置:首页 > 其它

Leetcode Candy

2017-07-17 11:18 357 查看
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?

因为至少有一个糖果,初始时将candy数组赋值为1.因为高rating的children要比neighbors获得更多的糖果。所以先进行一次遍历,高rating的children的糖果数比前一个children 多1.但这样处理完,还存在一种不符合情况的没有处理。前一个children的糖果数为1,而后一个rating更低的children糖果数也为1,这样是不符合题目要求的。因此从尾到头开始遍历,如果前一个children的rating大于后一个children,则设置其糖果数为max(candy[i],candy[i+1])
,这样就修正了该情况,同时也会因为该修改而修改其他children的糖果数,从而符合题目要求。

代码如下:

class Solution {
public:
int candy(vector<int>& ratings) {
int num = ratings.size();
int candy[num],total=0;;
for(int i=0;i<num;i++)
candy[i] = 1;

for(int i=1;i<num;i++)
{
if(ratings[i] > ratings[i-1])
candy[i] = candy[i-1]+1;
}

total = candy[num-1];
for(int i=num-2;i>=0;i--)
{
if(ratings[i] > ratings[i+1])
{
candy[i] = max(candy[i],candy[i+1]+1);
}
total += candy[i];
}

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