LeetCode C++ 135. Candy【Greedy】困难
发布日期:2021-07-01 02:58:28
浏览次数:2
分类:技术文章
本文共 1613 字,大约阅读时间需要 5 分钟。
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?
Example 1:
Input: [1,0,2]Output: 5Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
Example 2:
Input: [1,2,2]Output: 4Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions.
题意:老师想给孩子们分发糖果,有 N
个孩子站成了一条直线,老师会根据每个孩子的表现,预先给他们评分。按照以下要求,帮助老师给这些孩子分发糖果:
- 每个孩子至少分配到
1
个糖果。 - 相邻的孩子中,评分高的孩子必须获得更多的糖果。
那么这样下来,老师至少需要准备多少颗糖果呢?
解法 贪心
感觉和PAT(乙级)2020年秋季考试中的胖达与盆盆奶差不多,代码也很简单。关键在于,一定要在确定一边之后,再确定另一边——例如先让每一个孩子和左边比较,然后再和右边比较;如果两边一起考虑就会顾此失彼。
class Solution { public: int candy(vector & ratings) { if (ratings.size() <= 1) return ratings.size(); int n = ratings.size(), ans = 0; vector candies(n, 1); for (int i = 1; i < n; ++i) if (ratings[i] > ratings[i - 1] && candies[i] <= candies[i - 1]) candies[i] = candies[i - 1] + 1; //当前的值大于左部的 for (int i = n - 2; i >= 0; --i) if (ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]) candies[i] = candies[i + 1] + 1; //当前的值大于右部的 for (int i = 0; i < n; ++i) ans += candies[i]; return ans; }};
运行效率如下:
执行用时:44 ms, 在所有 C++ 提交中击败了59.76% 的用户内存消耗:16.9 MB, 在所有 C++ 提交中击败了65.11% 的用户
转载地址:https://memcpy0.blog.csdn.net/article/details/111602874 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
第一次来,支持一个
[***.219.124.196]2024年04月11日 08时56分15秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
dubbo学习笔记 十一 dubbo-rpc之模块
2019-05-01
motan学习笔记 五 opentracing学习入门
2019-05-01
求列表最长子序列
2019-05-01
字符串的排序
2019-05-01
内存分配(mallloc,calloc,realloc,new)
2019-05-01
网络编程之 Socket函数 (二)
2019-05-01
网络编程之 Socket的模式(一) --- “阻塞/非阻塞” 与 “同步/异步”
2019-05-01
ffmpeg & mplayer & vlc 手册
2019-05-01
Go语言并发组件
2019-05-01
简析STUN协议
2019-05-01
使用 Minidumps 和 Visual Studio .NET 进行崩溃后调试
2019-05-01
Debug 和 Release 编译方式的本质区别
2019-05-01
struts返回xml数据例子
2019-05-01
内存对齐详解
2019-05-01
秋招总结(一)-C++归纳
2019-05-01
秋招总结(三)-操作系统归纳
2019-05-01
带缓冲I/O 和不带缓冲I/O的区别与联系
2019-05-01
LINUX CP命令详解
2019-05-01
source insight快捷键及使用技巧
2019-05-01
映 射 ALT 键
2019-05-01