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?
Have you met this question in a real interview? Yes ExampleGiven 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 ? class Solution { public: int candy(vector<int>& ratings) { vector<int> dp(ratings.size(),1); for(int i=0;i<ratings.size()-1;i++) if(ratings[i]<ratings[i+1]) dp[i+1] = max(dp[i+1],dp[i]+1); for(int i=ratings.size()-1;i>=1;i--) if(ratings[i]<ratings[i-1]) dp[i-1] = max(dp[i-1],dp[i]+1); return accumulate(dp.begin(),dp.end(),0); } };