LintCode_412 Candy

来源:互联网 发布:北京java薪资待遇 编辑:程序博客网 时间:2024/06/17 16:52

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?

Example

Given ratings = [1, 2], return 3.

Given ratings = [1, 1, 1], return 3.

Given ratings = [1, 2, 2], return 4. ([1,2,1]).


分析:其实题目描述的有点问题,不是评级越高的小孩可以得到更多的糖果,从第三个样例中可以看出来,应该是“相邻两人里评级高的,可以得到更多的糖果”,一开始可以假设每个小孩都1颗糖果,如果第i个小孩比i-1个小孩rating高,那么糖果数也得比他高,和i+1个小孩比也是这样,于是可以从前往后扫描一遍,再从后往前扫描一遍。

[cpp] view plain copy
 print?
  1. class Solution {    
  2. public:    
  3.             
  4.     int candy(vector<int>& ratings) {    
  5.                 
  6.         vector<int> dp(ratings.size(),1);    
  7.         for(int i=0;i<ratings.size()-1;i++)    
  8.             if(ratings[i]<ratings[i+1])    
  9.                 dp[i+1] = max(dp[i+1],dp[i]+1);    
  10.                
  11.         for(int i=ratings.size()-1;i>=1;i--)    
  12.             if(ratings[i]<ratings[i-1])    
  13.                 dp[i-1] = max(dp[i-1],dp[i]+1);    
  14.                 
  15.         return accumulate(dp.begin(),dp.end(),0);    
  16.     }    
  17. };   



0 0
原创粉丝点击