[Leetcode] 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?

 

先从左向右扫描一遍,如果当前小盆宇比左边的小盆宇评分高,就多给他一颗糖,然后再从右向左扫描一遍。

 

 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 };

 

posted @ 2014-04-01 18:23  Eason Liu  阅读(384)  评论(0编辑  收藏  举报