LeetCode Candy

原题链接在这里:https://leetcode.com/problems/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?

Trapping Rain Water相似。每个孩子能拿到多少糖取决于左右两边,和能储存多少水取决于Math.min(左侧挡板最大值, 右侧挡板最大值)一个道理。

所以先用leftNum保存根据左侧邻居,该孩子能拿到多少糖,若是rating比左侧高,就要比左侧多拿一个,否则只需要拿一个。右侧同理。

最后在走一遍,取左右侧中较大值加入res中。

Time O(n), Space O(n).

AC Java:

 1 public class Solution {
 2     public int candy(int[] ratings) {
 3         if(ratings == null || ratings.length == 0){
 4             return 0;
 5         }
 6         
 7         //get how many candies based on left neighbour
 8         int [] leftNum = new int[ratings.length];
 9         leftNum[0] = 1;
10         for(int i = 1; i<ratings.length; i++){
11             if(ratings[i] > ratings[i-1]){
12                 leftNum[i] = leftNum[i-1]+1;
13             }else{
14                 leftNum[i] = 1;
15             }
16         }
17         
18         //get how many candies base on right neighbour
19         int [] rightNum = new int[ratings.length];
20         rightNum[ratings.length-1] = 1;
21         for(int i = ratings.length-2; i>=0; i--){
22             if(ratings[i] > ratings[i+1]){
23                 rightNum[i] = rightNum[i+1]+1;
24             }else{
25                 rightNum[i] = 1;
26             }
27         }
28         
29         //total number of candies
30         int res = 0;
31         for(int i = 0; i<ratings.length; i++){
32             res += Math.max(leftNum[i], rightNum[i]);
33         }
34         return res;
35     }
36 }

 

posted @ 2015-11-05 07:52  Dylan_Java_NYC  阅读(204)  评论(0编辑  收藏  举报