Candy
2014-01-28 01:22
585 查看
Candy
Total Accepted: 5341 TotalSubmissions: 32340My Submissions
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?
从ratings的左往右扫,如果右边的ratings > 左边的rating, 右边的candy = max(右边的candy, 左边的candy +1).
从ratings的右往左扫,如果左边的ratings > 右边的rating, 左边的candy = max(左边的candy, 右边的candy +1).
加总
O(N) time, O(N) space.
public class Solution { public int candy(int[] ratings) { int[] candy = new int[ratings.length]; for (int i = 1; i < ratings.length; i++) { if (ratings[i] > ratings[i - 1]) candy[i] = Math.max(candy[i],candy[i - 1] + 1); } int sum = 0; for (int i = ratings.length - 1; i >= 1; i--) { if (ratings[i - 1] > ratings[i]) candy[i - 1] = Math.max(candy[i-1],candy[i] + 1); sum += candy[i]; } sum+= candy[0]; return sum + candy.length; } }
相关文章推荐
- HDU 1034 Candy Sharing Game
- POJ 3083 Children of the Candy Corn DFS及BFS搜索
- POJ 3083 Children of the Candy Corn
- POJ-3083 Children of the Candy Corn 解题报告(搜索) 广搜深搜走迷宫
- pku3083Children of the Candy Corn-模拟+bfs
- poj 3083 Children of the Candy Corn(dfs+bfs)
- UVA 10482 The Candyman Can
- H.O.T candy
- Children of the Candy Corn (bfs+dfs)
- hdu 4465 Candy(2012 ACM-ICPC 成都现场赛)
- [leetcode] Candy
- [LeetCode] Candy
- [LeetCode] Candy
- [Leetcode] Candy (Java)
- CF 390C:Inna and Candy Boxes
- leetCode解题报告之Candy(简单回溯)
- hdu 4322 Candy 费用流
- LeetCode_Candy
- Candy
- leetcode 150: Candy