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

LeetCode Candy

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

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

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

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

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

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