首页 > 其他 > 详细

Candy

时间:2014-07-01 23:57:34      阅读:452      评论:0      收藏:0      [点我收藏+]

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;
    }
};

 

Candy,布布扣,bubuko.com

Candy

原文:http://www.cnblogs.com/awy-blog/p/3816409.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!