[LeetCode] 130: Candy
2017-09-10 20:53
369 查看
[Problem]
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?
[Solution]
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?
[Solution]
class Solution { public: int candy(vector<int> &ratings) { // Note: The Solution object is instantiated only once and is reused by each test case. if(ratings.size() == 0) return 0; // initial int dp[ratings.size()]; for(int i = 0; i < ratings.size(); ++i)dp[i] = 1; // dp for(int i = 1; i < ratings.size(); ++i){ if(ratings[i] > ratings[i-1]){ dp[i] = max(dp[i], dp[i-1] + 1); } } for(int i = ratings.size()-2; i >= 0; --i){ if(ratings[i] > ratings[i+1]){ dp[i] = max(dp[i], dp[i+1] + 1); } } // get result int res = 0; for(int i = 0; i < ratings.size(); ++i){ res += dp[i]; } return res; } };说明:版权所有,转载请注明出处。Coder007的博客
相关文章推荐
- LeetCode 130 Merge k Sorted Lists
- Candy [leetcode]
- [leetcode] Candy
- (LeetCode 135) Candy N个孩子站成一排,给每个人设定一个权重
- 【leetcode】candy
- [LeetCode#130]Surrounded Regions
- [LeetCode]Candy
- Leetcode 135 Candy 解题报告
- [LeetCode] Candy
- Leetcode Candy
- LeetCode130 Surrounded Regions
- [LeetCode 135] Candy
- [LeetCode] Candy
- leetcode[130] Surrounded Regions
- [LeetCode] Candy
- [Leetcode 100] 130 Jump Game II
- Leetcode candy中c++解法
- [LeetCode]题解(python):135-Candy
- LeetCode 笔记25 Candy (艰难的调试)
- LeetCode: Candy [135]