码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Candy

时间:2015-11-05 08:51:02      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

原题链接在这里:https://leetcode.com/problems/candy/

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 }

 

LeetCode Candy

标签:

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/4938112.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!