分发糖果
2016-06-27 10:42
369 查看
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 n=ratings.size();
vector<int> count(n,1);
for(int i=1;i<n;i++)
{
if(ratings[i]>ratings[i-1])
count[i]=count[i-1]+1;
}
for(int i=n-2;i>=0;i--)
{
if(ratings[i]>ratings[i+1] && count[i]<=count[i+1])
count[i]=count[i+1]+1;
}
int res=0;
for(int i=0;i<n;i++)
res+=count[i];
return res;
}
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 n=ratings.size();
vector<int> count(n,1);
for(int i=1;i<n;i++)
{
if(ratings[i]>ratings[i-1])
count[i]=count[i-1]+1;
}
for(int i=n-2;i>=0;i--)
{
if(ratings[i]>ratings[i+1] && count[i]<=count[i+1])
count[i]=count[i+1]+1;
}
int res=0;
for(int i=0;i<n;i++)
res+=count[i];
return res;
}
相关文章推荐
- Android Studio Android UI控件学习笔记
- 网页上的“返回上一页”的几种实现代码
- POP Animation 和 layoutSubviews 的冲突
- js选择器全面解析
- Android应用程序的debug属性
- session过期时间
- 处理并发中奖概率方法
- Java swing使用皮肤后出现Component creation must be done on Event Dispatch Thread错误解决方法
- curl获取登录状态
- 程序员如何保持优秀
- 暑期二(A)(hdu2041)
- keepalived 配置使用
- java 写http压测
- win7系统如何将浏览器版本调至较低版本 win7系统将浏览器版本调至较低版本的方法
- Java基础之内部类(1)
- 168. Excel Sheet Column Title Excel表列名 和 171. Excel Sheet Column Number
- Java NIO Scatter / Gather
- 奇数阶魔方阵算法分析
- Java中如何遍历Map对象的4种方法
- Hibernate基础之九:多对多,单/双向关联 @ManyToOne @OneToMany