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?

Example

Given ratings = [1, 2], return 3.

Given ratings = [1, 1, 1], return 3.

Given ratings = [1, 2, 2], return 4. ([1,2,1]).

分析:

扫两遍。第一遍从左往右扫,保证右边大的candy数大于左边小的,否则为1.

第二遍从右往左扫,保证左边大的candy数比右边小的大,而且还必须不能低于自己当前的candy数。

 1 public class Solution {
 2     /**
 3      * @param ratings Children's ratings
 4      * @return the minimum candies you must give
 5      */
 6     public int candy(int[] ratings) {
 7         if (ratings == null || ratings.length == 0) {
 8             return 0;
 9         }
10  
11         int[] candies = new int[ratings.length];
12         candies[0] = 1;
13      
14         //from let to right, assign one more than to its right neighbor if its right 
15         // neighbor has higher rating
16         for (int i = 1; i < ratings.length; i++) {
17             if (ratings[i] > ratings[i - 1]) {
18                 candies[i] = candies[i - 1] + 1;
19             } else { 
20                 // if not ascending, assign 1
21                 candies[i] = 1;
22             }
23         }
24      
25         int total = candies[ratings.length - 1];
26         //from right to left, assign one more candy to its left neighbor if its left neighbor
27         // if its left neighbor has higher rating.
28         for (int i = ratings.length - 2; i >= 0; i--) {
29             int cur = 1;
30             if (ratings[i] > ratings[i + 1]) {
31                 cur = candies[i + 1] + 1;
32             }
33             candies[i] = Math.max(cur, candies[i]);
34             total += candies[i];
35         }
36         return total;
37     }
38 }

 

posted @ 2016-07-21 05:52  北叶青藤  阅读(198)  评论(0编辑  收藏  举报