leetCode #135 Candy
来源:互联网 发布:淘宝客佣金谁给的 编辑:程序博客网 时间:2024/06/05 03:46
题目:给一排小孩发糖果,每个小孩有自己的评分,评分高的小孩得到的糖果比评分低的左右邻居要多。每个小孩至少一个糖果。问最少发多少糖果?
分析:
对于一个顺序上升或者下降的评分序列,小孩得到的糖果最少也得是递增/递减的
比如
评分 1 3 5 7 8
糖果 1 2 3 4 5
评分 9 7 4 3 1
糖果 5 4 3 2 1
而对于非递增/递减的评分序列,可以拆分成几段上升/下降的序列
另外可以考虑,从左到右扫描评分数组,使之满足最少的递增情况的糖果分发
然后从右到左扫描,使之满足最少的递减情况的糖果分发。
答案:
class Solution {public: int candy(vector<int>& ratings) { vector<int> candies; candies.push_back(1); for (int i = 1; i< ratings.size(); i++){ if (ratings[i-1] < ratings[i]) candies.push_back(candies[i-1] +1);// i should has more than i-1 else candies.push_back(1); } for (int i = ratings.size() - 2; i>=0; i--){ if (ratings[i] > ratings[i+1] && candies[i] <= candies[i+1]) candies[i] = (candies[i+1] +1);// i should has more than i+1 } int sum = 0; for (int i = 0; i< candies.size(); i++){ sum +=candies[i]; } return sum; }};
0 0
- [Leetcode 135, Hard] Candy
- LeetCode: Candy [135]
- [leetcode 135] Candy
- LeetCode(135) Candy
- [LeetCode 135]Candy
- LeetCode 135 Candy
- leetcode || 135、Candy
- [leetcode-135]Candy(java)
- leetcode 135: Candy
- leetCode #135 Candy
- 【LeetCode-135】Candy
- Leetcode (135) Candy
- LeetCode(135)Candy
- Leetcode. 135 Candy(Hard)
- LeetCode 135 Candy
- LeetCode 135 : Candy
- leetcode 135 —— Candy
- LeetCode 135:candy 题解 Python
- PHPExcel类的导出
- Spring的注解形式:@Repository
- 机器学习实战之KNN算法
- MFC之滚动条控件Scroll Bar
- Unity3D架构系列之- FSM有限状态机设计二
- leetCode #135 Candy
- How to access body of Custom tags in JSP tutorial
- CUDA tutorial 1
- 交换分区设置
- swift 总结3
- 面向对象三个基本元素,五个基本原则
- HIVE学习笔记 二 精简版
- 链表环问题研究
- 为什么你的APP不如人?因为你没有让它“活”起来