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

[leetcode]Candy

时间:2014-08-05 02:55:38      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   for   ar   代码   div   

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?

算法思路:

双向各扫描一次,第一次正向扫描,寻找递增序列,遇到ratings[i] > ratings[i - 1],则将candy[i] = candy[i - 1];

第二次寻找逆向递增序列(递减序列),遇到ratings[i] > ratings[i + 1],则candy[i] = Math.max(candy[i + 1] + 1,candy[i])

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

优化,单边扫描,双指针,扫描过程中找到严格递增和递减序列,递增序列则根据个数,将candy从1开始逐个增加,

递减序列需要注意:首先根据元素个数,逆向从1逐个增加。遇到最大值,则同样candy[i] = Math.max(candy[i + 1] + 1,candy[i]);

实现起来,代码略麻烦.....下次见。。。。

 

[leetcode]Candy,布布扣,bubuko.com

[leetcode]Candy

标签:style   blog   http   color   for   ar   代码   div   

原文地址:http://www.cnblogs.com/huntfor/p/3891324.html

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