Leetcode问题:
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?
思路:想了很久。想到维持递减序列,当递减序列结束的时候计算出递减序列中各个最终的高度。可是,竟然不对。。
看到网上的策略:顺着一遍,两两比较,根据题意让右边的值大于左边的值。再反着一遍,两两比较,根据题意让左边的值大于右边的值。
这么简单直白的思路,保证了任何一个数不管是其左邻居还是右邻居,都满足题意。
可是,怎么想不到呢?
class Solution {
public:
int candy(vector<int> &ratings) {
int n = ratings.size();
if(n == 0)
return 0;
else if(n == 1)
return 1;
vector<int> A;
for(int i=0;i<n;i++)
A.push_back(1);
//正着顺一遍
for(int i=1;i<n;i++)
if(ratings[i] > ratings[i-1])
A[i] = A[i-1] + 1;
//反着顺一遍
for(int i=n-2;i>=0;i--)
if(ratings[i] > ratings[i+1] && A[i] <= A[i+1])
A[i] = A[i+1] + 1;
int sum = 0;
for(int i=0;i<n;i++)
sum += A[i];
return sum;
}
};