Java for LeetCode 135 Candy
2015-06-03 12:02
645 查看
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?
解题思路:
双向爬坡问题,从前往后、从后往前各扫一遍,JAVA实现如下:
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?
解题思路:
双向爬坡问题,从前往后、从后往前各扫一遍,JAVA实现如下:
public int candy(int[] ratings) { int sum = 0; int[] candies = new int[ratings.length]; for (int i = 0; i < ratings.length - 1; i++) if (ratings[i] < ratings[i + 1]) candies[i + 1] = candies[i] + 1; for (int i = ratings.length - 2; i >= 0; i--) if (ratings[i + 1] < ratings[i]) candies[i] = Math.max(candies[i], candies[i + 1] + 1); for (int i = 0; i < candies.length; i++) sum += 1 + candies[i]; return sum; }
相关文章推荐
- struts2 jsp提交到action出现中文乱码问题
- java个人学习笔记:多态
- 二叉树的存储结构
- Eclipse下导入外部jar包的3种方式
- struts1简单入门使用实例
- 单元测试之TestNG与spring集成
- java内存分配 常量池详解
- 超详细在Ubuntu下安装JDK图文解析
- Unsupported major.minor version 51.0(jdk版本错误)
- java基础入门-泛型(1)-为什么需要使用泛型?
- java基础入门-泛型(1)-为什么需要使用泛型?
- eclipse安装反编译插件
- 关于Springmvc 处理静态资源的问题
- java 全角字符半角字符转换
- struts2中的Action详解
- 疯狂Java学习笔记(69)---------Lock
- Vijava 学习笔记之(获取用户指定自定义规范)
- eclipse可视化布局显示与真机不对
- MyEclipse从数据库反向生成实体类之Hibernate方式 反向工程
- java.lang.IllegalStateException: No output folder