leetcode刷题系列C++-candy
2016-02-22 16:23
731 查看
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?
Subscribe to see which companies asked this question
class Solution {
public:
int candy(vector<int>& ratings) {
int length = ratings.size();
vector<int> increment(length);
for(int i = 1,inc = 1; i < length; ++i)
{
if(ratings[i] > ratings[i - 1])
{
increment[i] = max(inc++,increment[i]);
}
else
{
inc = 1;
}
}
for(int i = length-2, inc = 1; i >= 0; --i)
{
if(ratings[i] > ratings[i + 1])
{
increment[i] = max(inc++,increment[i]);
}
else
{
inc = 1;
}
}
return accumulate(&increment[0],&increment[0] + length,length);
}
};
从左到右扫描一遍
然后从右到左扫描一遍
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?
Subscribe to see which companies asked this question
class Solution {
public:
int candy(vector<int>& ratings) {
int length = ratings.size();
vector<int> increment(length);
for(int i = 1,inc = 1; i < length; ++i)
{
if(ratings[i] > ratings[i - 1])
{
increment[i] = max(inc++,increment[i]);
}
else
{
inc = 1;
}
}
for(int i = length-2, inc = 1; i >= 0; --i)
{
if(ratings[i] > ratings[i + 1])
{
increment[i] = max(inc++,increment[i]);
}
else
{
inc = 1;
}
}
return accumulate(&increment[0],&increment[0] + length,length);
}
};
从左到右扫描一遍
然后从右到左扫描一遍
相关文章推荐
- 用C语言实现二分查找算法
- C++实现链表的基本操作及测试用例
- C语言 常用的时间函数
- c++primer阅读笔记之函数
- 1030. Travel Plan (30)
- C++ template —— 智能指针(十二)
- C++ template —— 类型区分(十一)
- C++面向对象编程<六>:Big Three,三个特殊函数
- C++ template —— 表达式模板(十)
- C++ template —— template metaprogram(九)
- 1029. Median (25)
- iOS开发 兼容OC和C语言
- leetcode刷题系列C++-Gas Station
- 1028. List Sorting (25)
- C++设计模式之——抽象工厂模式(AbstractFactoryPattern)
- 根据C语言改写的java实现的,判定九宫格是否合法。记录
- C语言的位运算的优势 !
- C++学习笔记:为什么不要重载逻辑与和逻辑或&& || 操作符
- 发布 Victor 串口控件 1.5.0.5 for C++ Builder 10 (CX) / XE8 / XE7 / XE6
- C++学习笔记:重载 函数调用符()