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?
题意:n 个小孩,每个小孩有一个评分。给小孩发糖。要求:
1)每个小孩至少一颗糖
2)评分高的小孩发的糖比他旁边两个小孩的多
因此最少需要多少糖果才够分?
解题思路:
遍历两边,首先每个人得一块糖,第一遍从左到右,若当前点比前一个点高就比前者多一块。
这样保证了在一个方向上满足了要求。第二遍从右往左,若左右两点,左侧高于右侧,但
左侧的糖果数不多于右侧,则左侧糖果数等于右侧糖果数+1,这就保证了另一个方向上满足要求。
最后将各个位置的糖果数累加起来就可以了。
代码实现:
class Solution { public: int candy(vector<int> &ratings) { int n=ratings.size(); //candy set vector<int>Candy(n,1); //from left to right for(int i(0);i<n-1;i++){ if(ratings[i+1]>ratings[i]) Candy[i+1]=Candy[i]+1; } //from right to left for(int j=n-1;j>0;j--){ if(ratings[j-1]>ratings[j]&&Candy[j-1]<=Candy[j]) Candy[j-1]=Candy[j]+1; } //add all int sum(0); for(auto a:Candy) sum+=a; return sum; } };