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

Leetcode: Candy

时间:2014-09-20 14:54:38      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   ar   for   div   sp   

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?

Tapping Rain Water问题相似, 用DP。基本思路就是进行两次扫描,一次从左往右,一次从右往左。第一次扫描的时候维护从左到右对于每一个小孩所需要最少的糖果数量,存入数组对应元素中,第二次扫描的时候维护从右到左所需的最少糖果数,并且比较将左边和右边大的糖果数量存入结果数组对应元素中。这样两遍扫描之后就可以得到每一个所需要的最最少糖果量,从而累加得出结果。方法只需要两次扫描,所以时间复杂度是O(2*n)=O(n)。空间上需要一个长度为n的数组,复杂度是O(n)。

 1 public class Solution {
 2     public int candy(int[] ratings) {
 3         if (ratings==null || ratings.length==0) return 0;
 4         int[] left = new int[ratings.length];
 5         int[] right = new int[ratings.length];
 6         int sum = 0;
 7         for (int i=0; i<left.length; i++) {
 8             if (i == 0) left[i] = 1;
 9             else if (ratings[i] > ratings[i-1]) left[i] = left[i-1] + 1;
10             else left[i] = 1;
11         }
12         for (int j=right.length-1; j>=0; j--) {
13             if (j == right.length-1) right[j] = 1;
14             else if (ratings[j] > ratings[j+1]) right[j] = right[j+1] + 1;
15             else right[j] = 1;
16         }
17         for (int k=0; k<left.length; k++) {
18             left[k] = Math.max(left[k], right[k]);
19             sum += left[k];
20         }
21         return sum;
22     }
23 }

 

Leetcode: Candy

标签:style   blog   http   color   io   ar   for   div   sp   

原文地址:http://www.cnblogs.com/EdwardLiu/p/3983218.html

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