LeetCode-Candy
来源:互联网 发布:Linux解压并新建文件夹 编辑:程序博客网 时间:2024/06/07 12:40
1. Candy(Hard)
Description
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?
Analysis
分析题意,每个Children至少有一颗Candy,我们可以初始化每个Children的Candy的数量为1,然后比较每个Children的和他前后的Children的rating,如果他的rating高于前后的Children的,则他的Candy数量必须至少比其他两个Children的更大值大1。但是前后一起比较并不好实现,我们可以先正序遍历ratings,如果当前Children的rating大于前一个Children的rating,则他的Candy数比前一个大1。然后倒序遍历一个,做相同的操作,就可以满足题目要求。
代码:
class Solution {public: int candy(vector<int>& ratings) { int result = 0; vector<int> candys = ratings; for (int &candy : candys) { candy = 1; } for (int i = 0; i < ratings.size(); i++) { if(ratings[i] > ratings[i-1]) candys[i] = candys[i-1] + 1; } for (int i = ratings.size()-1; i > 0; i--) { if(ratings[i-1] > ratings[i]) candys[i-1] = max(candys[i]+1,candys[i-1]); } for (int candy : candys) { result += candy; } return result; }};
阅读全文
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
- uva 10765 (求去掉每一个一个点 可以得到联通块的个数 )
- webView加载数据内容
- FPGA顶会
- 如何使用星际文件传输网络(IPFS)搭建区块链服务(一)
- 从源码角度分析nodejs如何处理一个HTTP请求
- LeetCode-Candy
- 合并K个有序数组
- 字符串拼接与java常用基础
- 2017 年最流行的 15 个数据科学 Python 库
- Redis学习-Sets
- 程序媛:数据库操作之封装为函数(sqlite3 )
- PAT——1019数字黑洞
- 数据结构—队列的顺序和链式存储
- linux内核源码中max和min的宏实现