LeetCode135—Candy

来源:互联网 发布:mac 查找文件路径 编辑:程序博客网 时间:2024/05/29 02:43

原题

原题链接

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?


分析

N个小孩,每个小孩有一个等级,且每个小孩的等级如果比他临近的小孩高,那么他将得到更多的糖果。
求最少需要多少糖果才能满足上述要求,且每个小孩至少一个糖果。

模拟这个过程,可能会想到:
求最少需要多少糖果,先每个人分配一个,再根据等级依次加一个糖果。

但上述思路是会有问题的,那就是对于小孩i来说,假设他的等级既高于小孩i1又高于小孩i+1,那么他得到的糖果就要比小孩i1和小孩i+1的糖果中的较多者要多一个,这样看的话一次循环可能搞不定,因为第一次循环中在计算第i个小孩的糖果时,第i+1个小孩的数据还没出来呢。

因此两次循环,一次从左到右,一次从右往左。


代码

class Solution {public:    int candy( vector <int>& ratings)        {            int N= ratings.size();            vector<int>count(N,1);            for(int i=1;i<ratings.size();i++)            {                if(ratings[i]>ratings[i-1])                    count[i]=count[i-1]+1;            }            for(int i=N-1;i>0;i--)            {                if(ratings[i]<ratings[i-1])                {                    count[i-1]=max(count[i]+1,count[i-1]);                }            }            return accumulate(count.begin(),count.end(),0);        }};
1 0
原创粉丝点击