【leetcode】Candy
2014-07-22 22:36
357 查看
Candy
链接:https://oj.leetcode.com/problems/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?
方法:
前后两遍扫描。注意题中没有提到如果相邻两个数相等的情况,从提交情况应该是相等归于小于一类。
代码如下:
int candy(vector<int> &ratings) {
int size = ratings.size();
if(size <= 0 ) return 0;
vector<int> candies(size, 1);
for(int i=1; i < size; ++i)
{
if(ratings[i] > ratings[i-1]){
candies[i] = candies[i-1] + 1;
}/*else if( ratings[i] == ratings[i -1])
{
candies[i] = candies[i - 1];
}*/
}
int result = candies[size - 1];
for(int i = size - 2; i >= 0; --i)
{
if( ratings[i] > ratings[i+1])
{
if( candies[i] < candies[i+1] + 1)
candies[i] = candies[i+1] + 1;
}/*else if( ratings[i] == ratings[i+1])
{
if( candies[i] < candies[i + 1])
candies[i] = candies[i+1];
}*/
result += candies[i];
}
return result;
}
相关文章推荐
- 【LeetCode练习题】Candy
- [LeetCode] Candy
- 【LeetCode笔记】Candy
- 【leetcode】 Candy (hard,pick one)
- LeetCode:Candy
- [leetcode] Candy Java
- [LeetCode] Candy 分糖果问题
- [LeetCode] Candy
- leetcode-Candy
- [LeetCode] Candy
- leetcode题目:Candy
- [LeetCode] 135. candy
- leetcode之candy
- leetcode 135 —— Candy
- LeetCode 笔记25 Candy (艰难的调试)
- [leetcode-135]Candy(java)
- 【LeetCode candy】
- LeetCode: Candy 解题报告
- LeetCode:Candy
- LeetCode2.1.22 (Candy)