LeetCode-135.Candy
来源:互联网 发布:冷漠的文字软件 编辑:程序博客网 时间:2024/06/05 21:01
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?
跟题LeetCode-42.Trapping Rain Water 类似,使用两次动态规划
public int Candy(int[] ratings) { int n = ratings.Length; if (n < 2) return 1; int[] left = new int[n]; left[0] = 1; for (int i = 1; i < n; i++) { left[i] = 1; if (ratings[i] > ratings[i - 1]) left[i] += left[i - 1]; } int[] right = new int[n]; right[n - 1] = left[n - 1]; int res= left[n - 1]; for (int i = n-2; i >=0; i--) { right[i] = 1; if (ratings[i] > ratings[i + 1]) right[i] += right[i + 1]; res += Math.Max(left[i], right[i]); } return res; }
优化减少空间,省去right数组
public int Candy(int[] ratings) { int n = ratings.Length; if (n < 2) return 1; int[] left = new int[n]; left[0] = 1; for (int i = 1; i < n; i++) { left[i] = 1; if (ratings[i] > ratings[i - 1]) left[i] += left[i - 1]; } int res= left[n - 1],right; for (int i = n-2; i >=0; i--) { right = 1; if (ratings[i] > ratings[i + 1]) right += left[i + 1]; res += Math.Max(left[i], right); left[i] = right; } return res; }
参考 http://blog.csdn.net/linhuanmars/article/details/21424783
0 0
- [LeetCode]135.Candy
- 135. Candy Leetcode Python
- [Leetcode] 135. Candy
- [leetcode] 135.Candy
- [leetcode] 135. Candy
- leetcode 135. Candy
- leetcode 135. Candy
- [LeetCode]135. Candy
- LeetCode 135. Candy
- Leetcode 135. Candy
- leetcode.135. Candy
- LeetCode 135. Candy
- [leetcode] 【数组】 135. Candy
- LeetCode-135.Candy
- LeetCode 135. Candy
- Leetcode 135. Candy
- leetcode-135. Candy
- [LeetCode] 135. Candy
- iOS 模拟器安装.app
- 剑指offer-面试题8:旋转数组中的最小数字
- Hbuilder开发移动新闻客户端(二)
- Activiti工作流引擎使用
- 配置eclipse的java代码注解的模板
- LeetCode-135.Candy
- 5G到底什么时候来,它究竟能给我们带来什么?
- more命令
- C++异常处理
- 一个基于组合模式的游戏地图系统
- Auto Layout的初步运用。
- 两个成员的类模板
- Context是怎么泄露的:Handlers & Inner Classes
- 第一次使用Android Studio时你应该知道的一切配置