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

leetcode || 135、Candy

时间:2015-04-29 17:18:10      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:leetcode   贪心   

problem:

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?

Hide Tags
 Greedy
题意: 给小盆友发糖果,属性高的糖果要更多

thinking:

(1)一道简单的贪心题目,为何通过率这么低??题目中根本没提属性相等时怎么发糖果。又是一道不严谨的题目。提交发现,

122的小盆友发了4个糖果,说明,第三个小盆友发了1个糖果,换做你是小盆友,你会高兴吗...

(2)撇开相等的情况不说,这道题只要处理好递减的情况就行了。递增或者乱序好处理些

code:

class Solution{
    public:
int candy(vector<int> &ratings) {
    int Total = 0;    /// Total candies
    int length = 0;  /// Continuous descending length of rate
    int nPreCanCnt = 1; /// Previous child's candy count
    int beforeDenc = nPreCanCnt;
    if(ratings.begin() != ratings.end())
    {
        Total++; //Counting the first child's candy (1).
        for(vector<int>::iterator i = ratings.begin()+1; i!= ratings.end(); i++)
        {
            if(*i < *(i-1))
            {
                length++;
                if(beforeDenc <= length)
                {
                    Total++;
                }
                Total += length;
                nPreCanCnt = 1;    //This step is important, it ensures that once we leave the decending sequence, candy number start from 1
            }
            else
            {
                int curCanCnt = 0;
                if(*i > *(i-1))
                { 
                    curCanCnt = (nPreCanCnt + 1);
                }
                else
                {
                    curCanCnt = 1;
                }
                Total += curCanCnt;
                nPreCanCnt = curCanCnt;
                length = 0;    //reset length of decending sequence
                beforeDenc = curCanCnt;
            }
        }
    }
    return Total;
}
};


leetcode || 135、Candy

标签:leetcode   贪心   

原文地址:http://blog.csdn.net/hustyangju/article/details/45367185

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