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

135. Candy(Array; Sort)

时间:2015-10-03 16:47:12      阅读:107      评论: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?

思路:neighbor=>元素值与前、后元素有关=>前向、后向两次扫描。

class Solution {
public:
    int candy(vector<int> &ratings) {
        vector<int> new_ratings(ratings.size(), 1);
        for(int i = 1; i < ratings.size(); i++) //for the first time, scan from beginning
        {
            if(ratings[i] > ratings[i-1]) 
            {
                new_ratings[i] = new_ratings[i-1]+1;
            }
          
        }
        for(int i=ratings.size()-2;i>=0;i--){  //for the second time, scan from the end
            if(ratings[i]>ratings[i+1]&&new_ratings[i]<=new_ratings[i+1]){  
                new_ratings[i]=new_ratings[i+1]+1;  
            }  
        }  
        int sum=0;  
        for(int i=0;i<new_ratings.size();i++){  
            sum+=new_ratings[i];  
        }  
          
        return sum;  
    }
};

 

135. Candy(Array; Sort)

标签:

原文地址:http://www.cnblogs.com/qionglouyuyu/p/4853463.html

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