LeetCode: Candy
2014-08-23 13:57
239 查看
[b]LeetCode: Candy[/b]
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?
地址:https://oj.leetcode.com/problems/candy/
算法:这道题用动态规划可以解决,之前在王道的练习赛上有遇到过,分析见我之前的一篇文章:/article/6286416.html
代码:
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?
地址:https://oj.leetcode.com/problems/candy/
算法:这道题用动态规划可以解决,之前在王道的练习赛上有遇到过,分析见我之前的一篇文章:/article/6286416.html
代码:
class Solution { public: int candy(vector<int> &ratings) { int n = ratings.size(); vector<int> num_candys(n); if(n == 0) return 0; return subSolution(0,n-1,num_candys,ratings); } int subSolution(int s, int e, vector<int> &num_candys,vector<int> &ratings){ if(s == e){ num_candys[s] = 1; return 1; }else{ int total = 0; int mid = (s + e) >> 1; int left = subSolution(s,mid,num_candys,ratings); int right = subSolution(mid+1,e,num_candys,ratings); if(ratings[mid] == ratings[mid+1]){ return left + right; }else if(ratings[mid] > ratings[mid+1]){ if(num_candys[mid] > num_candys[mid+1]) return left + right; else{ total += (num_candys[mid+1] + 1 - num_candys[mid]); num_candys[mid] = num_candys[mid+1] + 1; int totalAdd = 0; for(int i = mid-1; i >= s; --i){ if(ratings[i] <= ratings[i+1] || (ratings[i] > ratings[i+1] && num_candys[i] > num_candys[i+1])) break; else{ total += (num_candys[i+1] + 1 - num_candys[i]); num_candys[i] = num_candys[i+1] + 1; } } return left + right + total; } }else{ if(num_candys[mid] < num_candys[mid+1]) return left + right; else{ total += (num_candys[mid] + 1 - num_candys[mid+1]); num_candys[mid+1] = num_candys[mid] + 1; for(int i = mid+2; i <= e; ++i){ if(ratings[i] <= ratings[i-1] || (ratings[i] > ratings[i-1] && num_candys[i] > num_candys[i-1])) break; else{ total += (num_candys[i-1] + 1 - num_candys[i]); num_candys[i] = num_candys[i-1] + 1; } } return left + right + total; } } } } };
相关文章推荐
- [leetcode] Candy Java
- leetcode-Candy
- [LeetCode] Candy
- leetcode题目:Candy
- Leetcode -- Candy
- 【LeetCode-135】Candy
- LeetCode 笔记25 Candy (艰难的调试)
- Candy leetcode java
- [LeetCode]Candy
- Leetcode135(Candy)
- LeetCode: Candy 解题报告
- leetcode:Candy
- leetcode — candy
- 【LeetCode练习题】Candy
- [LeetCode] Candy
- LeetCode Candy
- 【LeetCode笔记】Candy
- Leetcode|Candy
- LeetCode--------candy
- 【LeetCode candy】