[LeetCode]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?
思考:提交了好多次,终于弄明白题意。有一点是需要注意的,当相邻两个小孩的等级值相同时,他们的糖果数可以不同。
遍历两次。第一次从左往右,确定右邻居合法,即当等级值变大时,小孩糖果数加1,否则为1。第二次遍历从右往左,确定左邻居合法,即当等级值变大时并且原先遍历不合法时,小孩糖果数加1,否则不变。
class Solution { public: int candy(vector<int> &ratings) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int ret=0; int len=ratings.size(); int *p=new int[len]; memset(p,0,sizeof(int)*len); int i; p[0]=1; for(i=1;i<len;i++) { if(ratings[i]>ratings[i-1]) p[i]=p[i-1]+1; else p[i]=1; } for(i=len-2;i>=0;i--) { if(ratings[i]>ratings[i+1]&&(p[i]<=p[i+1])) p[i]=p[i+1]+1; } for(i=0;i<len;i++) { ret+=p[i]; } delete []p; return ret; } };