leetcode-candy
2017-05-08 10:03
447 查看
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?
解题思路:
1、从左到右扫描,如果右边比左边分数高,右边在左边糖果数基础上+1,否则糖果数为1
2、从右边到左扫描,如果左边分数比右边大,且左边糖果树不小于或等于右边糖果数,那么左边糖果数在右边糖果数基础上+1
3、最后求糖果数总和
public class Solution { public int candy(int[] ratings) { if(ratings.length==1) return 1; int[] candy=new int[ratings.length]; candy[0]=1;// for(int i=1;i<ratings.length;i++){ if(ratings[i-1]<ratings[i]){//如果右边比左边分数大,就糖果数加1 candy[i]=candy[i-1]+1; }else{ candy[i]=1;//否则糖果数为1 } } for(int i=ratings.length-2;i>=0;i--){ if(ratings[i]>ratings[i+1]&&candy[i]<=candy[i+1]){ candy[i]=candy[i+1]+1; } } int sum=0; for(int i=0;i<ratings.length;i++){ sum+=candy[i]; } return sum; } }
相关文章推荐
- LeetCode——Candy
- LeetCode-Candy
- LeetCode 笔记25 Candy (艰难的调试)
- [LeetCode] Candy
- 【LeetCode candy】
- 4.19 leetcode -19 candy
- [LeetCode] Candy (分糖果),时间复杂度O(n),空间复杂度为O(1),且只需遍历一次的实现
- leetCode_Candy
- [Leetcode] Candy
- LeetCode (Candy)
- leetcode之candy
- leetcode:greedy: Candy(135)
- [LeetCode] Candy (分糖果),时间复杂度O(n),空间复杂度为O(1),且只需遍历一次的实现
- LeetCode | Candy
- leetcode[135] Candy
- [LeetCode] Candy
- LeetCode题解:Candy
- [Leetcode] Candy (Java)
- [Leetcode][JAVA] Candy
- Leetcode: Candy