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

leetcode_135_Candy

时间:2015-06-23 15:34:56      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:leetcode   c++   array   

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?


分析:

开始的时候想,找最小值,然后分两边计算,但是该想法不可取。
后来看答案,才知道,左右各扫描一遍,取最大值。


//方法一:左右各扫描一遍。时间复杂度 O(n) ,空间复杂度 O(n)
class Solution {
public:
    int candy(vector<int>& ratings) {
        const int N = ratings.size();
        int cur = 1;
        vector<int> temp(N, 1);
        
        for(int i = 0; i <= N-2; i++)
        {
            if(ratings[i+1] > ratings[i])
                temp[i+1] = ++cur;
            else
                cur = 1;
        }
        
        cur = 1;
        for(int i = N - 2; i >= 0; i--)
        {
            if(ratings[i+1] < ratings[i])
                temp[i] = max(++cur, temp[i]);
            else
                cur = 1;
        }
        
        int sum = 0;
        for(int i = 0; i < N; i++)
            sum += temp[i];
        return sum;
    }
};


leetcode_135_Candy

标签:leetcode   c++   array   

原文地址:http://blog.csdn.net/keyyuanxin/article/details/46605771

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