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?
就是个坑啊!
首先,竟然允许相邻的2个人同样ranking!!!!他们还怎么做朋友!
其次,对于ranking为 123333321的这组,你猜~~~
class Solution { public: int candy(vector<int> &ratings) { int size = ratings.size(); vector<int> num(size,1); vector<int> min; if(size == 1)return 1; if(size == 2) if(ratings[0]==ratings[1])return 2; else return 3; for(int i = 1 ; i < size-1 ;i++) { if(ratings[i-1]>=ratings[i] && ratings[i] <= ratings[i+1])min.push_back(i); } int i=0; while(i+1<size && ratings[i+1] >= ratings[i]) { if(ratings[i+1] == ratings[i]) //num[i+1] = 1; ; else num[i+1] = num[i]+1; i++; } i = size -1; while(i>=1 && ratings[i-1] >= ratings[i]) {if(ratings[i-1] == ratings[i]) //num[i-1] = 1; ; else num[i-1] = num[i]+1; i--;} for(int j = 0 ; j < min.size(); j++) { int t = min[j]; i=t; while(i >= 0 && ratings[i-1] >= ratings[i]) { if(num[i -1] <= num[i]) if(ratings[i-1] == ratings[i]) //num[i-1] = num[i] ; else num[i-1] = num[i]+1; i--; } i=t; while(i <size && ratings[i+1] >= ratings[i]) { if(num[i +1] <= num[i]) if(ratings[i+1] == ratings[i]) //num[i+1] = num[i] ; else num[i+1] = num[i] +1; i++; } } int re = 0; for( i = 0 ; i < size ;i++) re += num[i]; return re; } };