【LeetCode】Candy
2013-12-30 13:11
260 查看
Candy
Total Accepted: 4149 Total Submissions: 26052 My Submissions
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?
【解题思路】
应该是上升序列和下降序列的合集吧。
声明一个数组candyNum[],表示下标为i的人所拥有的糖果数目。
初始化时每个人所拥有的糖果数目为1。
int len = ratings.length
从开头上升过程。
从0开始循环到len-2。
如果ratings[i] < ratings[i+1],那么candyNum[i+1] = candyNum[i]+1;
从结尾上升过程。
从len-2循环到0。
如果ratings[i+1] > ratings[i],并且candyNum[i+1] <= candyNum[i],那么candyNum[i+1] <= candyNum[i]
其实就是这样一个过程。
最后循环candNum,累加就是最后结果。
Java AC
Total Accepted: 4149 Total Submissions: 26052 My Submissions
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?
【解题思路】
应该是上升序列和下降序列的合集吧。
声明一个数组candyNum[],表示下标为i的人所拥有的糖果数目。
初始化时每个人所拥有的糖果数目为1。
int len = ratings.length
从开头上升过程。
从0开始循环到len-2。
如果ratings[i] < ratings[i+1],那么candyNum[i+1] = candyNum[i]+1;
从结尾上升过程。
从len-2循环到0。
如果ratings[i+1] > ratings[i],并且candyNum[i+1] <= candyNum[i],那么candyNum[i+1] <= candyNum[i]
其实就是这样一个过程。
最后循环candNum,累加就是最后结果。
Java AC
public class Solution { public int candy(int[] ratings) { if(ratings == null || ratings.length == 0){ return 0; } int len = ratings.length; int candyNum[] = new int[len]; for(int i = 0; i < len; i++){ candyNum[i] = 1; } for(int i = 1; i < len; i++){ if(ratings[i] > ratings[i-1]){ candyNum[i] = candyNum[i-1]+1; } } for(int i = len-2; i >= 0; i--){ if(ratings[i] > ratings[i+1] && candyNum[i] <= candyNum[i+1]){ candyNum[i] = candyNum[i+1]+1; } } int allCandy = 0; for(int i = 0; i < len; i++){ allCandy += candyNum[i]; } return allCandy; } }
相关文章推荐
- 【LeetCode】Candy
- [LeetCode] Candy 分糖果问题
- leetcode135~Candy
- Leetcode225: Candy
- LeetCode-Candy
- [leetcode]Candy
- [LeetCode] Candy
- Leetcode - candy
- leetcode 135 —— Candy
- [leetcode-135]Candy(java)
- [LeetCode]Candy
- leetcode Candy
- LeetCode:Candy
- LeetCode2.1.22 (Candy)
- leetcode 138: Candy (incompleted)
- Leetcode Candy
- LeetCode -- Candy
- Leetcode: Candy
- [LeetCode]题解(python):135-Candy
- leetcode之Candy