首页 > 其他 > 详细

LeetCode Candy

时间:2014-09-03 21:15:27      阅读:224      评论:0      收藏:0      [点我收藏+]

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?

 

解法:从左到右比较,第一个发1个,下一个比前一个rating高就+1,否则发1个。

   然后从右到左,最后一个发1个,前一个比后一个rating高就+1,否则发1个。

  取两次得到的值的最大值,然后累加。

 

 1 public class Solution {
 2     public int candy(int[] ratings) {
 3             int[] leftCandys = new int[ratings.length];
 4             int[] rightCandys = new int[ratings.length];
 5             int[] candys = new int[ratings.length];
 6             int sum=0;
 7             leftCandys[0]=1;
 8             for (int i = 0; i < ratings.length-1; i++) {
 9                 if (ratings[i]<ratings[i+1]) {
10                     leftCandys[i+1]=leftCandys[i]+1;
11                 }else {
12                     leftCandys[i+1]=1;
13                 }
14             }
15             
16             rightCandys[ratings.length-1]=1;
17             for (int i = ratings.length-1; i >0; i--) {
18                 if (ratings[i]<ratings[i-1]) {
19                     rightCandys[i-1]=rightCandys[i]+1;
20                 }else {
21                     rightCandys[i-1]=1;
22                 }
23             }
24             
25             for (int i = 0; i < candys.length; i++) {
26                 candys[i]=Math.max(leftCandys[i], rightCandys[i]);
27                 sum=sum+candys[i];
28             }
29             return sum;
30     }
31 }

 

LeetCode Candy

原文:http://www.cnblogs.com/birdhack/p/3954537.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!