LeetCode-135.Candy
2016-06-06 17:03
232 查看
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 类似,使用两次动态规划
优化减少空间,省去right数组
参考 http://blog.csdn.net/linhuanmars/article/details/21424783
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 ; 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 ; 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 ; 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
相关文章推荐
- C++动态规划之最长公子序列实例
- C++动态规划之背包问题解决方法
- C#使用动态规划解决0-1背包问题实例分析
- 动态规划
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- C++ 动态规划
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02