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

[LeetCode]Candy

时间:2015-02-12 10:48:33      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:java   leetcode   贪心法   

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?


分别从前往后,再从后往前 遍历,关键是max中的表达式


public class Solution {
    public int candy(int[] ratings) {
    	int len = ratings.length;
    	int res[] = new int[len];
    	int ret = 0;
        for(int i=1,inc =1;i<len;i++){
        	if(ratings[i-1]<ratings[i]) {
        		res[i] = Math.max(res[i], inc++);
        	}else{
        		inc = 1;
        	}
        }
        for(int i=len-2,inc =1;i>=0;i--){
        	if(ratings[i]>ratings[i+1]){
        		res[i] = Math.max(res[i], inc++);
        	}else{
        		inc = 1;
        	}
        }
        for(int i:res){
        	ret += i;
        }
        return ret+len;
    }
}




[LeetCode]Candy

标签:java   leetcode   贪心法   

原文地址:http://blog.csdn.net/guorudi/article/details/43759313

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