[leetcode] Candy
来源:互联网 发布:linux下jdk怎么卸载 编辑:程序博客网 时间:2024/06/16 09:36
Description
Problem Link
一群小孩站成线。每个小孩有一个分值。现在要分糖果,需要满足两个条件:
1. 每个小孩至少要有一颗糖。
2. 分值较高的小孩要比他的左右拿更多的糖。
问最少需要多少糖果。
e.g.scores[] = {1,3,5,7,7,7,4,1}candy[] = {1,2,3,4,1,3,2,1}ANS = 1+2+3+4+1+3+2+1 = 17
Possible Solution
贪心
分析: 如果从左到右扫一遍,唯一能确定的就是递增序列,例如,[1,3,5,7], 那么最优解是[1,2,3,4]。
做法:序列一共三种,递增,递减,不变,对于递增的序列从左向右扫的时候确定答案,对于递减序列从右向左扫确定答案,对于不变序列,除了头和尾,其他分到的糖果都为1.
附代码:
class Solution {public: int candy(vector<int>& ratings) { int n = ratings.size(); vector<int> candy(n,0); for (int i = 0; i < n; ++i) { bool bol = true; if (i != 0 && ratings[i] > ratings[i-1]) bol = false; if (i != n-1 && ratings[i] > ratings[i+1]) bol = false; if (bol) candy[i] = 1; } for (int i = 1; i < n; ++i) if (ratings[i] > ratings[i-1]) candy[i] = candy[i-1] + 1; for (int i = n-2; i >= 0; --i) if (ratings[i] > ratings[i+1]) candy[i] = std::max(candy[i+1]+1, candy[i]); int ans = 0; for (int i = 0; i < n; ++i) ans += candy[i]; return ans; }};
0 0
- Leetcode: Candy
- LeetCode:Candy
- [leetcode]Candy
- Leetcode: Candy
- 【leetcode】Candy
- LeetCode:Candy
- [LeetCode] Candy
- [LeetCode]Candy
- [LeetCode] Candy
- 【LeetCode】Candy
- LeetCode | Candy
- Leetcode: Candy
- Candy - LeetCode
- leetcode Candy
- LeetCode Candy
- candy leetcode
- Candy -- LeetCode
- [LeetCode] Candy
- 写给进军大数据的你们:
- MySQL聚合函数
- 【leetcode】63. Unique Paths II
- Android -- Handler消息机制简析
- C#随机函数Random()的用法
- [leetcode] Candy
- (备忘)myeclipse2014使用前的一些配置
- 第八周—鸡兔同笼
- 设计模式——建造者模式
- 个人MYSQL操作记录
- CLR无法从COM 上下文*****转换为COM上下文*****,这种状态已持续60秒。
- Activity生命周期详解
- tensorflow安装(一)
- kettle数据同步