LeetCode 题解工作台
分发糖果
n 个孩子站成一排。给你一个整数数组 ratings 表示每个孩子的评分。 你需要按照以下要求,给这些孩子分发糖果: 每个孩子至少分配到 1 个糖果。 相邻两个孩子中,评分更高的那个会获得更多的糖果。 请你给每个孩子分发糖果,计算并返回需要准备的 最少糖果数目 。 示例 1: 输入: ratings…
2
题型
7
代码语言
3
相关题
当前训练重点
困难 · 贪心·invariant
答案摘要
我们初始化两个数组 和 ,其中 表示当前孩子比左边孩子评分高时,当前孩子至少应该获得的糖果数,而 表示当前孩子比右边孩子评分高时,当前孩子至少应该获得的糖果数。初始时 , 。 我们从左到右遍历一遍,如果当前孩子比左边孩子评分高,则 ;同理,我们从右到左遍历一遍,如果当前孩子比右边孩子评分高,则 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
n 个孩子站成一排。给你一个整数数组 ratings 表示每个孩子的评分。
你需要按照以下要求,给这些孩子分发糖果:
- 每个孩子至少分配到
1个糖果。 - 相邻两个孩子中,评分更高的那个会获得更多的糖果。
请你给每个孩子分发糖果,计算并返回需要准备的 最少糖果数目 。
示例 1:
输入:ratings = [1,0,2] 输出:5 解释:你可以分别给第一个、第二个、第三个孩子分发 2、1、2 颗糖果。
示例 2:
输入:ratings = [1,2,2]
输出:4
解释:你可以分别给第一个、第二个、第三个孩子分发 1、2、1 颗糖果。
第三个孩子只得到 1 颗糖果,这满足题面中的两个条件。
提示:
n == ratings.length1 <= n <= 2 * 1040 <= ratings[i] <= 2 * 104
解题思路
方法一:两次遍历
我们初始化两个数组 和 ,其中 表示当前孩子比左边孩子评分高时,当前孩子至少应该获得的糖果数,而 表示当前孩子比右边孩子评分高时,当前孩子至少应该获得的糖果数。初始时 , 。
我们从左到右遍历一遍,如果当前孩子比左边孩子评分高,则 ;同理,我们从右到左遍历一遍,如果当前孩子比右边孩子评分高,则 。
最后,我们遍历一遍评分数组,每个孩子至少应该获得的糖果数为 和 中的最大值,将它们累加起来即为答案。
时间复杂度 ,空间复杂度 。其中 是评分数组的长度。
class Solution:
def candy(self, ratings: List[int]) -> int:
n = len(ratings)
left = [1] * n
right = [1] * n
for i in range(1, n):
if ratings[i] > ratings[i - 1]:
left[i] = left[i - 1] + 1
for i in range(n - 2, -1, -1):
if ratings[i] > ratings[i + 1]:
right[i] = right[i + 1] + 1
return sum(max(a, b) for a, b in zip(left, right))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for a clear understanding of greedy algorithms and how to implement the left-to-right and right-to-left passes.
- question_mark
Test the candidate’s ability to minimize the number of candies through an optimal distribution while respecting the invariant.
- question_mark
Expect the candidate to handle edge cases such as consecutive children with equal ratings or large arrays efficiently.
常见陷阱
外企场景- error
Failing to correctly handle the right-to-left pass, potentially leading to incorrect candy assignments.
- error
Not initializing candies properly or misunderstanding the invariant conditions for rating comparisons.
- error
Omitting edge cases, such as when all ratings are equal or when there's only one child.
进阶变体
外企场景- arrow_right_alt
Extend the problem by requiring the solution to work for multiple test cases.
- arrow_right_alt
Modify the problem to allow varying minimum candy distributions, such as children with ratings greater than 5.
- arrow_right_alt
Increase the constraints by considering very large input sizes, testing the efficiency of the algorithm further.