【leetcode】Candy
2014-07-16 19:46
375 查看
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?
题解:
第一个孩子给一颗糖,然后从左到右遍历rate数组,如果孩子i+1的rate比孩子i的rate高,那么孩子i+1得到的糖果数目比孩子i得到的糖果数目多1;如果孩子i+1的rate比孩子i的rate低,那么就给孩子i+1一颗糖;
从右往左遍历rate数组,如果当前遍历的孩子i的rate比他右边的孩子的rate高,那么他得到的糖果就比他右边的孩子得到的糖果多1.
累加rate中所有的值,得到总的最少糖果数目。
代码如下:
在17行的循环,需要判断i-1个孩子当前获得的糖果数目是否真的比第i个孩子的少,如果真的少,才需要+1.例如:
ratings = {4,2,3,4,1}的时候,第一遍遍历得到的count数组是{1,1,2,3,1},此时从后往前遍历的时候ratings[3] > ratings[4],但是count[3]已经大于count[4]了,所以不需要更新count[3] = count[4]+1。
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?
题解:
第一个孩子给一颗糖,然后从左到右遍历rate数组,如果孩子i+1的rate比孩子i的rate高,那么孩子i+1得到的糖果数目比孩子i得到的糖果数目多1;如果孩子i+1的rate比孩子i的rate低,那么就给孩子i+1一颗糖;
从右往左遍历rate数组,如果当前遍历的孩子i的rate比他右边的孩子的rate高,那么他得到的糖果就比他右边的孩子得到的糖果多1.
累加rate中所有的值,得到总的最少糖果数目。
代码如下:
public class Solution { public int candy(int[] ratings) { if(ratings.length == 0) return 0; int[] count = new int[ratings.length]; Arrays.fill(count, 1); for(int i = 1;i <= ratings.length-1;i++){ if(ratings[i]> ratings[i-1] ) count[i] = count[i-1] + 1; } int sum = 0; for(int i = ratings.length-1;i >= 1;i--){ sum += count[i]; if(ratings[i-1] > ratings[i] && count[i-1] <= count[i]) count[i-1] = count[i]+ 1; } return count[0] + sum; } }
在17行的循环,需要判断i-1个孩子当前获得的糖果数目是否真的比第i个孩子的少,如果真的少,才需要+1.例如:
ratings = {4,2,3,4,1}的时候,第一遍遍历得到的count数组是{1,1,2,3,1},此时从后往前遍历的时候ratings[3] > ratings[4],但是count[3]已经大于count[4]了,所以不需要更新count[3] = count[4]+1。
相关文章推荐
- leetcode_Candy
- LeetCode:Candy
- 4.19 leetcode -19 candy
- LeetCode 135:candy 题解 Python
- 117_leetcode_Candy
- [LeetCode] Candy
- leetcode :Candy
- [LeetCode]Candy
- https://leetcode.com/problems/candy/
- Candy -- leetcode
- LeetCode:Candy
- Leetcode Candy
- LeetCode_Candy
- LeetCode139: Candy
- 【leetcode】Candy
- Leetcode 135 Candy
- LeetCode || Candy
- [leetcode]Candy @ Python
- [LeetCode]Candy
- 开始leetcode day9:Candy