码迷,mamicode.com
首页 > 其他好文 > 详细

Candy

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

标签:style   blog   color   问题   算法   for   

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

标签:style   blog   color   问题   算法   for   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!