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?

思路:分糖果问题,用贪心算法。我们用num[i]表示第i个孩子的糖果数目,如果i+1孩子比i孩子的ratings大,则i+1的孩子糖果数目为i孩子糖果数目+1.如果i孩子比i+1孩子ratings大,怎么办,等从左往右开始遍历结束,我们从右往左开始,把之前忽略的情况给补上,就可以了。时间复杂度为O(n),空间复杂度为O(n)。

class Solution {
public:
    int candy(vector<int> &ratings) {
        int n=ratings.size();
        if(n<=0)
            return 0;
        vector<int> num(n,1);
        for(int i=1;i<n;i++)
        {
            if(ratings[i-1]<ratings[i])
            {
                num[i]=num[i-1]+1;
            }
        }
        for(int i=n-2;i>=0;i--)
        {
            if(ratings[i]>ratings[i+1] && num[i]<=num[i+1])
            {
                num[i]=num[i+1]+1;
            }
        }
        int sum=0;
        for(int i=0;i<n;i++)
        {
            sum+=num[i];
        }
        return sum;
    }
};

 

posted @ 2014-06-30 12:55  Awy  阅读(183)  评论(0编辑  收藏  举报