Candy
来源:互联网 发布:淘宝网妈妈斗篷 编辑:程序博客网 时间:2024/04/29 15:18
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?
题目很诡异。当两个相邻的值相等时,孩子得到的糖果不一定相等。做法和trapping rain一样。
做法:先从左扫描一遍,得到一个每个孩子和其左边孩子对比的结果,如果rating大于左边的,就左边值+1;否则为1
再从右扫一遍,得到孩子和右边孩子的对比结果,同上。同时得到当前孩子必须得到的糖果数:max(左侧扫描结果, 右侧扫描结果)然后加到总结果上。
public int candy(int[] ratings) { int n = ratings.length; int[] c = new int[n]; int[] result = new int[n]; if (n <= 1) { return n == 0 ? 0 :1; } result[0] = 1; result[n-1] = 1; for (int i = 1; i < n; i++) { if (ratings[i] > ratings[i-1]) { result[i] = result[i-1]+1; } else { result[i] = 1; } } int total = result[n-1]; for (int i = n-2; i >= 0; i--) { int cur; if (ratings[i] > ratings[i+1]) { cur = result[i+1]+1; } else { cur = 1; } total += Math.max(result[i], cur); result[i] = cur; } return total; }
0 0
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- candy
- Candy
- Candy
- Candy
- Candy
- 用PHP实现同一个帐号不允许同时登陆,只允许一个帐号登录?
- Valid Parentheses
- zoj 3811 (2014 牡丹江网赛 C) Untrusted Patrol
- linux下 实时网络流量监控命令
- QTableWidgetItem类文档
- Candy
- Problem-A 老衲的嘱托
- Java引用详解
- 使用sar进行性能分析
- MFC开发自己的截图工具
- 算法:找出数组中未出现的那个数字
- 在Visual C++中用ADO进行数据库编程
- Android 判断Service是否已经运行
- zoj 3811 Untrusted Patrol(dsf+并査集+邻接表)