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 class Solution {
 2 public:
 3     int candy(vector<int> &ratings) {
 4         int res = 0;
 5         int n = ratings.size();
 6         if (n == 0) {
 7             return res;
 8         }
 9         int *t = new int[n];
10         for (int i = 0; i < n; ++i) {
11             t[i] = 1;
12         }
13         for (int i = 1; i < n; ++i) {
14             if (ratings[i] > ratings[i-1]) {
15                 t[i] = t[i-1] + 1;
16             }
17         }
18         for (int i = n - 1; i >= 1; --i) {
19             if (ratings[i] < ratings[i-1]) {
20                 t[i-1] = (t[i] + 1) > t[i-1] ? (t[i] + 1) : t[i-1];
21             }
22         }
23         for (int i = 0; i < n; ++i) {
24             res += t[i];
25         }
26         return res;
27     }
28 };

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-11-08
  • 2022-01-08
  • 2021-10-07
  • 2021-10-16
  • 2021-07-23
  • 2021-09-22
猜你喜欢
  • 2022-03-03
  • 2021-09-22
  • 2022-01-13
  • 2022-02-15
  • 2022-12-23
  • 2021-05-21
  • 2022-12-23
相关资源
相似解决方案