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

Candy

时间:2014-06-12 07:15:59      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   http   color   

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?

左右各扫描一遍

首先是从左向右扫描,若为第一个孩子或者当前的rating小于等于前一个的rating,该孩子给1颗糖,否则,该孩子的糖数为前一名孩子的糖数量加1。

然后是从右向左扫描,若为最后一个孩子或者当前的rating小于等于后一个的rating,该孩子给1颗糖,否则,该孩子的糖数为后一名孩子的糖数量加1。

每一位小孩得到的糖的数量为两次遍历给的糖数中较大的那个,然后遍历每个孩子,累计糖的数量,即得到结果。

 1 public int candy(int[] ratings) {
 2         int result[] = new int[ratings.length];
 3         for(int i=0;i<ratings.length;i++){
 4             result[i] = (i==0||ratings[i]<=ratings[i-1])?1:result[i-1]+1;
 5         }
 6         for(int i=ratings.length-1;i>=0;i--){
 7             int a = (i==ratings.length-1||ratings[i]<=ratings[i+1])?1:result[i+1]+1;
 8             result[i] = result[i]>a?result[i]:a;
 9         }
10         int max = 0;
11         for(int i=0;i<ratings.length;i++){
12             max+=result[i];
13         }
14         return max;
15     }

bubuko.com,布布扣

看了看题解,发现递归版本有一种叫备忘录的做法,不懂,o(╯□╰)o,有时间研究研究

Candy,布布扣,bubuko.com

Candy

标签:style   class   blog   code   http   color   

原文地址:http://www.cnblogs.com/apoptoxin/p/3782653.html

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