135. Candy
2017-12-27 16:43
288 查看
欢迎fork and star:Nowcoder-Repository-github
135. 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?
解析
这样前后两个遍历结果,思路采用一次遍历实现或者其他动态规划的思路实现
class Solution_135 { //题意:N个孩子站成一排,每个孩子分配一个分值。给这些孩子派发糖果,满足如下要求: //每个孩子至少一个 //分值更高的孩子比他的相邻位的孩子获得更多的糖果 //求至少分发多少糖果? public: int candy(vector<int> &ratings) { //采用左右遍历两次方法 const int len = ratings.size(); if (len==1) { return len; } vector<int> res(len,1); for (int i = 1; i < ratings.size();i++) { if (ratings[i]>ratings[i-1]) //右边大于左边 { res[i] = res[i - 1] + 1; //分配的糖果数 } } int ret = 0; for (int j = len - 2,ret=res[len-1]; j >= 0;j--) //bug 此处ret当做局部变量, { if (ratings[j]>ratings[j+1]&& res[j]<=res[j+1]) //左边大于右边且左边的糖果少于右边的糖果数 { res[j] = res[j + 1] + 1; } ret += res[j]; } return ret; } };
题目来源
135. Candy_leetcode牛客网
相关文章推荐
- 【LeetCode】135. Candy
- LeetCode 135. Candy
- 135. Candy
- LeetCode题解–135. Candy
- 135. Candy
- 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 (O(n)时间 O(n)和O(1)空间的两种实现)
- Hard-题目34:135. Candy
- 135. Candy
- Leetcode 135. Candy
- leetcode题解-135. Candy
- leetcode 135. Candy
- [Leetcode] 135. Candy
- 135. Candy