LeetCode||candy

来源:互联网 发布:明星p图软件 编辑:程序博客网 时间:2024/05/17 03:30

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?



class Solution {

public:
    int candy(vector<int> &ratings) {
/*


 遍历两边,首先每个人得一块糖,第一遍从左到右,若当前点比前一个点高就比前者多一块。
  这样保证了在一个方向上满足了要求。第二遍从右往左,若左右两点,左侧高于右侧,但
  左侧的糖果数不多于右侧,则左侧糖果数等于右侧糖果数+1,这就保证了另一个方向上满足要求
 */
        int n=ratings.size();
        vector<int> child(n);
        for(int i=0;i<n;i++)
            child[i]=1;
        int i=0;
        for(i=1;i<n;i++)
            {
            if(ratings[i]>ratings[i-1])
               child[i]=child[i-1]+1;
        }
        
        for(i=n-2;i>=0;i--)
            {
            if(ratings[i]>ratings[i+1]&&child[i]<=child[i+1])
               child[i]=child[i+1]+1;
        }
        
        return accumulate(child.begin(),child.end(),0);
    }
};