Candy - LeetCode
2014-01-23 06:50
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?
初始化所有小孩糖数目为1,从前往后扫描,如果第i个小孩等级比第i-1个高,那么i的糖数目等于i-1的糖数目+1;从后往前扫描,如果第i个的小孩的等级比i+1个小孩高,但是糖的数目却小或者相等,那么i的糖数目等于i+1的糖数目+1。
该算法时间复杂度为O(N)
算法代码如下:
出处: http://www.cnblogs.com/TenosDoIt/p/3389479.html
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,从前往后扫描,如果第i个小孩等级比第i-1个高,那么i的糖数目等于i-1的糖数目+1;从后往前扫描,如果第i个的小孩的等级比i+1个小孩高,但是糖的数目却小或者相等,那么i的糖数目等于i+1的糖数目+1。
该算法时间复杂度为O(N)
算法代码如下:
class Solution { public: int candy(vector<int> &ratings) { // Note: The Solution object is instantiated only once and is reused by each test case. int *candyNum = new int[ratings.size()];//每个小孩的糖数目 for(int i = 0; i < ratings.size(); i++) candyNum[i] = 1; for(int i = 1; i < ratings.size(); i++) if(ratings[i] > ratings[i-1]) candyNum[i] = candyNum[i-1] + 1; for(int i = ratings.size()-2; i>=0; i--) if(ratings[i] > ratings[i+1] && candyNum[i] <= candyNum[i+1]) candyNum[i] = candyNum[i+1] + 1; int result = 0; for(int i = 0; i < ratings.size(); i++) result += candyNum[i]; delete []candyNum; return result; } };
出处: http://www.cnblogs.com/TenosDoIt/p/3389479.html
相关文章推荐
- LeetCode——Candy
- [leetcode] Candy
- [LeetCode][JavaScript]Candy
- [LeetCode 题解]:Candy
- Candy - Leetcode
- LeetCode - Candy
- [Leetcode][JAVA] Candy
- LeetCode | Candy(分糖果问题)
- (LeetCode 135) Candy
- Leetcode_candy
- Leetcode 之Candy 分糖果问题。
- LeetCode题解:Candy
- [LeetCode]Candy, 解题报告
- 【leetcode】Candy
- Leetcode -- Candy
- LeetCode题解:Candy
- LeetCode: Candy
- LeetCode: Candy
- 6 Candy_Leetcode
- [LeetCode]Candy