LeetCode 135. Candy(糖果)
2016-05-27 00:22
435 查看
原题网址:https://leetcode.com/problems/candy/
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?
方法:两个指针,往返追逐。
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?
方法:两个指针,往返追逐。
public class Solution { public int candy(int[] ratings) { if (ratings == null || ratings.length == 0) return 0; if (ratings.length == 1) return 1; int[] candy = new int[ratings.length]; candy[0] = 1; // 最近的最高点 int high = 0; for(int i=1; i<ratings.length; i++) { if (ratings[i-1] <= ratings[i]) { int adjust = 1; for(int j=i-1; j>high; j--, adjust++) candy[j] = adjust; candy[high] = Math.max(candy[high], adjust); candy[i] = ratings[i-1]<ratings[i]? candy[i-1]+1:1; high = i; } } int adjust = 1; for(int j=ratings.length-1; j>high; j--, adjust++) candy[j] = adjust; candy[high] = Math.max(candy[high], adjust); int sum = 0; for(int i=0; i<ratings.length; i++) sum+=candy[i]; return sum; } }
相关文章推荐
- LeetCode 134. Gas Station(加油站)
- LeetCode 132. Palindrome Partitioning II(回文切分)
- LeetCode 133. Clone Graph(克隆图)
- 原型链(__proto__)
- makefile之VPATH和vpath的使用
- System.in.read()
- javascript的 Object 和 Function
- 快速多人游戏(1) - 介绍
- 概率世界
- 如何配置php运行环境
- Share Ubuntu Home Directories using Samba
- php性能测试工具--xhprof
- linux篇——centOs下的vim配置
- dll 子类化 记事本 相应自己的功能
- 用NSMutableAttributedString快速设置UIbutton Title/lable的文字:字体,大小,颜色
- 拦截器getmodel方法什么时候被调用(没搞懂有什么鸟用,自己搭的项目中用到了这个)
- Convention插件的使用(会涉及content目录,jsp必须放入这个下面才能映射成功基于注解的配置)
- Android 动画目录-概要
- 最新版SDWebImage的使用
- Spring组件扫描<context:component-scan/>使用详解