首页 > 代码库 > Candy

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?

左右各扫描一遍

首先是从左向右扫描,若为第一个孩子或者当前的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     }

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