LeetCode candy
2016-08-31 16:48
453 查看
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?
有N个孩子站在一条线。分配给每个孩子一个评级的价值。
你把糖果给这些孩子受到以下需求:
每个孩子必须至少有一个糖果。
评级较高的孩子得到更多的糖果比他们的邻居。
什么是你必须给的最低糖果吗?
以上内容是用有道翻译进行翻译
解题思路:------------------------------------------
每个小孩先发一块糖,然后从左向右进行遍历,如果arr[i]>arr[i-1],就在前一个人的糖的数目的基础上加1;
最后从右往左遍历,加上所有的糖(从右往左遍历是考虑到权值为:7 5 8 9 6 4 12)的情况
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?
有N个孩子站在一条线。分配给每个孩子一个评级的价值。
你把糖果给这些孩子受到以下需求:
每个孩子必须至少有一个糖果。
评级较高的孩子得到更多的糖果比他们的邻居。
什么是你必须给的最低糖果吗?
以上内容是用有道翻译进行翻译
解题思路:------------------------------------------
每个小孩先发一块糖,然后从左向右进行遍历,如果arr[i]>arr[i-1],就在前一个人的糖的数目的基础上加1;
最后从右往左遍历,加上所有的糖(从右往左遍历是考虑到权值为:7 5 8 9 6 4 12)的情况
import java.util.*; public class Solution { public int candy(int[] ratings) { if(ratings==null || ratings.length==0) { return 0; } int[] count = new int[ratings.length]; //每个孩子初始都有一个糖果 Arrays.fill(count,1); int sum = 0; for(int i=1;i<ratings.length;i++) { if(ratings[i]>ratings[i-1]) { count[i] = count[i-1]+1; } } for(int i=ratings.length-1;i>0;i--) { sum+=count[i]; if(ratings[i]<ratings[i-1] && count[i]>=count[i-1]) { count[i-1] = count[i]+1; } } sum+=count[0]; return sum; } }
相关文章推荐
- 经典面试题之字符串的全排列
- 解决win10系统flash player无法播放,升级
- Android之NestedScrollView 嵌套 RecyclerView 滑动冲突的问题
- PCI/PCIe那些事(3)-- Configuration Space Type 0/1
- 【C/C++】判断一个数是不是闰年
- 【如何正确使用const,static,extern】|那些人追的干货
- MLP多层感知机原理简介+代码详解
- Matlab计算机视觉/图像处理工具箱推荐
- ArcGIS 点的显示和隐藏、地图事件绑定
- [置顶] ubuntu12.04下编译vlc开源库
- Extjs4 封装echarts组件 2016.8.31
- 【基础学习】Android vector xml 将SVG转换成VectorDrawable 资源
- SQL常用语句
- 转:Eclipse常用快捷键
- 论Sava(),SaveOrUpdate(),Merge()区别
- 简单例子了解View的事件分发
- 分布式消息列队RocketMQ部署
- untiy 插件工具: 游戏中 策划数据Excel 导出到项目中
- Java 4种数组复制方式的性能比较
- 总结下最近Android混合开发的种种