LeetCode:Candy
2016-05-25 22:42
477 查看
Candy
Total Accepted: 52308 TotalSubmissions: 231427 Difficulty: Hard
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
Hide Tags
Greedy
思路:
1.先给每个小孩分1 个candy;
2.从左往右:如果,左<右,则右边小孩加1颗candy;
2.从右往左:如果,左>右,则左边小孩要比右边的candy多。
java code:
public class Solution { public int candy(int[] ratings) { int len = ratings.length; int[] candies = new int[len]; for(int i=0;i<len;i++) candies[i] = 1; for(int i=1;i<len;i++) { if(ratings[i-1] < ratings[i]) candies[i] = candies[i-1] + 1; } for(int i=len-1;i>0;i--) { if(ratings[i-1] > ratings[i]) candies[i-1] = Math.max(candies[i-1], candies[i]+1); } int ans = 0; for(int candy : candies) { ans += candy; } return ans; } }
相关文章推荐
- mysql导入时出现USING BTREE问题
- c++实验6--矩阵求和
- vertica-复杂sql导致crc校验错误
- Android Activity基础
- 析构函数与delete的思考
- LaTeX技巧006:使用不同的英文字体
- 是不是有经验的JavaEE开发者,看你json玩的6不6(下)
- EffectiveJava-第一章
- 一次优化列表页卡顿的经历
- tomcat源代码调试-maven篇
- js连接sqlite(IE内核浏览器适用)
- 手机开发实战41——手机模块设计2
- php数组分组问题
- C++作业6
- Jpeg(模拟)
- 信号量机制解决生产者--消费者问题
- struts2复制项目的时候需要注意的
- 手机开发实战40——手机模块设计1
- jQuery源码学习(一)
- Linux下Python设置vim和交互模式下自动补全