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

Candy

时间:2014-09-05 10:07:11      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:candy 分糖果   leetcode   

地址:https://oj.leetcode.com/problems/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必然获得比邻居更多的糖果。

public class Solution {
	public int candy(int[] ratings) {
		if(ratings.length == 0){
			return 0;
		}
		// 算法思想:从头到尾遍历数组,如果满足rating 更大 就给A[i-1]+1个,如果小就先赋值1.
		int []A = new int[ratings.length];
		A[0] = 1;
		for(int i=1;i<ratings.length;i++){
			if(ratings[i]>ratings[i-1]){
				A[i]= A[i-1]+1;
			}else {
				A[i] = 1;
			}
		}
		int ans = A[ratings.length-1];
		// 从尾到头再遍历一次,两次遍历过后就满足更高rating 有用更多糖果。
		for(int i=ratings.length-2;i>=0;i--){
			if(ratings[i]>ratings[i+1]){
				A[i] = Math.max(A[i], A[i+1]+1);
			}
			ans+= A[i];
		}
		return ans;
	}
}


 

Candy

标签:candy 分糖果   leetcode   

原文地址:http://blog.csdn.net/huruzun/article/details/39076283

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