Leetcode 动态规划 Candy
来源:互联网 发布:国产好的指纹锁 知乎 编辑:程序博客网 时间:2024/04/29 17:52
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
Candy
Total Accepted: 16494 Total Submissions: 87468My SubmissionsThere 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?
题意:n 个小孩,每个小孩有一个评分。给小孩发糖。要求:
1)每个小孩至少一颗糖
2)评分高的小孩发的糖比他旁边两个小孩的多
思路:左右 dp
用一个数组 candy[n],表示第 i 个小孩所应该发的最少糖果数
数组 ratings[n] 表示每个小孩的评分
1.从左到右扫描一遍, candy[i] = 1, if ratings[i] <= ratings[i-1] ; candy[i] = candy[i-1] + 1, if ratings[i] > ratings[i-1]
2.从右到左扫描一遍, candy[i] = candy[i], if ratings[i] <= ratings[i+1] ; candy[i] = max(candy[i], candy[i+1] + 1), if ratings[i] > ratings[i+1]
3.accumulate(candy, candy + n, 0)
复杂度: 时间 O(n), 空间 O(n)
int candy(vector<int> &ratings){int n = ratings.size();vector<int> candy(n, 1);for(int i = 1; i < n; ++i){candy[i] = ratings[i] <= ratings[i - 1] ? 1 : candy[i - 1] + 1;}for(int i = n - 2; i > -1;--i){candy[i] = ratings[i] <= ratings[i + 1] ? candy[i] : max(candy[i], candy[i + 1] + 1);}return accumulate(candy.begin(), candy.end(), 0);}
0 0
- Leetcode 动态规划 Candy
- 【LeetCode从零单排】No.135Candy(双向动态规划)
- 动态规划——candy
- candy(litecode动态规划)
- [LeetCode] [动态规划] Triangle
- LeetCode 之动态规划
- leetcode-动态规划:Triangle
- leetcode-动态规划
- LeetCode专题----动态规划
- LeetCode动态规划归纳
- LeetCode 动态规划
- 动态规划-leetcode小结
- 动态规划leetcode 回顾
- LeetCode动态规划
- leetcode 动态规划练习
- leetcode动态规划总结
- LeetCode基础--动态规划
- Leetcode: Candy
- hdu1285
- HDU 1418 抱歉【数学题】
- NYOJ题目14会场安排问题(贪心)
- hdu 1599 find the mincost route
- 堆排序
- Leetcode 动态规划 Candy
- 罗永浩vs王自如
- 伸展树
- 红黑树一
- Flume1.5.0的安装、部署、简单应用(含分布式、与hadoop2.2.0、hbase0.96的案例)
- 红黑树2
- Oozie安装及安装过程中存在的问题
- B树系列
- 堆