Leetcode: Candy
2013-10-02 12:12
295 查看
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?
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?
public class Solution { public int candy(int[] ratings) { // Note: The Solution object is instantiated only once and is reused by // each test case. int len = ratings.length; if(len == 0) return 0; int minSum = len; // Each child must have at least one candy. Better start this way. // I got bugs when start with minSum = 0 int curCandy = 0; int[] candy = new int[ratings.length]; for(int i = 1; i < len; i++){ if(ratings[i - 1] < ratings[i]) ++curCandy; else curCandy = 0; candy[i] = curCandy; } curCandy = 0; for(int i = len - 2; i >= 0;i--){ if(ratings[i] > ratings[i + 1]) ++curCandy; else curCandy = 0; minSum += Math.max(candy[i], curCandy); } minSum += candy[len - 1]; return minSum; } }
相关文章推荐
- 【LeetCode】Candy
- [LeetCode] Candy 分糖果问题
- leetcode135~Candy
- Leetcode225: Candy
- [LeetCode] Candy
- Leetcode - candy
- leetcode 135 —— Candy
- LeetCode: Candy
- [leetcode-135]Candy(java)
- [LeetCode]Candy
- leetcode Candy
- LeetCode:Candy
- LeetCode2.1.22 (Candy)
- Leetcode Candy
- LeetCode -- Candy
- Leetcode: Candy
- [LeetCode]题解(python):135-Candy
- leetcode之Candy
- leetcode_135_Candy_贪心
- [LeetCode] Candy