题目来源:Leetcode Algorithm ProblemSet 135
题目描述:
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
解题思路:
顺序走一遍,然后逆序走一遍。逆序的时候因为是ans[i] = max(ans[i+1] + 1, ans[i])。所以没有有破坏顺序走的那一边的性质,也就是ans[i] > ans[i-1] if ratings[i] > ratings[i-1]
题解代码:
- class Solution {
- public:
- int candy(vector<int>& ratings) {
- vector <int> ans(ratings.size(), 1);
- int sum = 0;
- for (int i = 1; i < ratings.size(); i ++) {
- if (ratings[i] > ratings[i-1])
- ans[i] = ans[i-1] + 1;
- }
- sum = ans[ratings.size()-1];
- for (int i = ratings.size() -2 ; i >=0; i --) {
- if (ratings[i] > ratings[i+1]) {
- ans[i] = max(ans[i+1] + 1, ans[i]);
- }
- sum += ans[i];
- }
- return sum;
- }
- };