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     int candy(vector<int> &ratings) {
 2         // IMPORTANT: Please reset any member data you declared, as
 3         // the same Solution instance will be reused for each test case.
 4         int num = ratings.size();
 5         int result = 0;
 6         vector<int> candies(num, 1);
 7         for(int i = 1; i < num; i++){
 8             if(ratings[i] > ratings[i-1] && candies[i] <= candies[i-1])
 9                 candies[i] = candies[i-1]+1;
10         }
11         for(int i = num-2; i >= 0; i--){
12             if(ratings[i] > ratings[i+1] && candies[i] <= candies[i+1])
13                 candies[i] = candies[i+1]+1;
14         }
15         for(int i = 0; i < num; i++)
16             result += candies[i];
17         return result;
18     }

 

posted on 2013-11-26 22:12  waruzhi  阅读(165)  评论(0编辑  收藏  举报

导航