标签:style blog io color ar sp for div on
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:
What is the minimum candies you must give?
首先。每个孩子至少有一个糖果,还要保证相邻孩子rating值大的获得更多的糖果。这个问题可以采取贪心的策略。首先每个孩子都分一个糖果。先从前往后遍历,如果后面的孩子rating值高,那么后面的孩子比前面相邻的孩子糖果数目要多一个。再从后往前遍历,如果前面孩子的rating值高,但是糖果数少,那么前面孩子比后面相邻孩子的糖果数目要多一个。这样就能保证相邻孩子之间,只要rating高,其拥有的糖果数就多。这个题目最容易忽略的细节是相邻包含前后相邻和后前相邻两种情况,所以要用到两次遍历。
1 class Solution { 2 public: 3 int candy(vector<int> &ratings) { 4 int len=ratings.size(); 5 int *a=new int [len]; 6 int i; 7 for(i=0;i<len;i++) 8 a[i]=1; 9 for(i=0;i<len-1;i++){ 10 if(ratings[i+1]>ratings[i])//如果后面的rating更大 11 a[i+1]=(a[i]+1); 12 13 } 14 for(i=len-1;i>0;i--){ 15 if(ratings[i-1]>ratings[i]&&a[i-1]<=a[i])//如果前面的rating更大,但是糖果数目少 16 a[i-1]=a[i]+1;//就将前面的candy数+1 17 } 18 int sum=0; 19 for(i=0;i<len;i++){ 20 sum+=a[i]; 21 } 22 23 return sum; 24 } 25 };
标签:style blog io color ar sp for div on
原文地址:http://www.cnblogs.com/zhoudayang/p/4098260.html