leetcode -- Candy
2013-10-03 10:39
225 查看
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?
[解题思路]
two pass scan, one pass from left to right, next pass from right to left
when find increment sequence, set candy by k, then increment k
something need to attention, the requirement of this problem is that only children with a higher rating need to get more
candies than their neighors, but if two child has the same rating, we do not need to give more candies
the time complexity is O(n), the space complexity is also O(n)
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?
[解题思路]
two pass scan, one pass from left to right, next pass from right to left
when find increment sequence, set candy by k, then increment k
something need to attention, the requirement of this problem is that only children with a higher rating need to get more
candies than their neighors, but if two child has the same rating, we do not need to give more candies
the time complexity is O(n), the space complexity is also O(n)
public class Solution { public int candy(int[] ratings) { int N = ratings.length; if(N == 0){ return N; } int[] candy = new int ; int sum = N; for(int i = 0, k = 1; i < N; i++){ if(i - 1 >= 0 && ratings[i] > ratings[i - 1]){ candy[i] = Math.max(k ++, candy[i]); } else { k = 1; } } for(int i = N - 1, k = 1; i >= 0; i--){ if(i + 1 < N && ratings[i] > ratings[i + 1]){ candy[i] = Math.max(k ++, candy[i]); } else { k = 1; } } for(int i = 0; i < N; i++){ sum += candy[i]; } return sum; } }
相关文章推荐
- LeetCode Candy Greedy
- LeetCode 135 : Candy
- Leetcode-candy
- leetCode 刷题记录 Candy
- Candy leetcode java
- Leetcode 动态规划 Candy
- Leetcode: Candy
- [LeetCode]135 Candy
- Candy [leetcode]
- LeetCode OJ Candy
- leetcode candy
- LeetCode: Candy
- 【LeetCode练习题】Candy
- [LeetCode] Candy
- LeetCode: Candy
- leetcode Candy
- Leetcode135——Candy
- LeetCode: Candy
- [LeetCode] Candy (分糖果),时间复杂度O(n),空间复杂度为O(1),且只需遍历一次的实现
- leetcode题目:Candy