python
from heapq import heappush, heappop
class Solution:
def eatenApples(self, apples: list[int], days: list[int]) -> int:
"""
计算可以吃掉的苹果的最大数目。
Args:
apples: 每天长出的苹果数量。
days: 苹果腐烂的天数。
Returns:
可以吃掉的苹果的最大数目。
"""
heap = [] # 存储 (腐烂时间, 苹果数量)
eaten_apples = 0
for i in range(len(apples)):
# 将当天长出的苹果加入堆中
if apples[i] > 0:
heappush(heap, (i + days[i], apples[i]))
# 每天吃掉一个苹果
while heap:
rotten_time, apple_count = heappop(heap)
if rotten_time > i: # 如果苹果还没腐烂
eaten_apples += 1
if apple_count > 1:
heappush(heap, (rotten_time, apple_count - 1))
break
else:
continue # 苹果已经腐烂,跳过
else:
# 如果堆为空,则当天没有苹果可以吃
pass
# 处理剩余的苹果
while heap:
rotten_time, apple_count = heappop(heap)
if rotten_time > len(apples):
eaten_apples += 1
if apple_count > 1:
heappush(heap, (rotten_time, apple_count - 1))
else:
continue
return eaten_apples
代码解释:
-
heap = []: 使用最小堆来存储苹果的腐烂时间。堆中的元素是 (腐烂时间, 苹果数量) 的元组。 最小堆保证了我们总是优先选择最快腐烂的苹果。
-
eaten_apples = 0: 初始化吃掉的苹果数量为 0。
-
for i in range(len(apples)): 遍历每一天。
-
if apples[i] > 0:: 如果当天有苹果长出来,则将其加入堆中。 heappush(heap, (i + days[i], apples[i])) 计算苹果的腐烂时间(当前天数 + 腐烂天数),并将其与苹果数量一起加入堆中。
-
while heap:: 每天尝试吃掉一个苹果。 只要堆中还有苹果,就循环执行。
-
rotten_time, apple_count = heappop(heap): 从堆中取出腐烂时间最早的苹果。
-
if rotten_time > i:: 检查苹果是否已经腐烂。 如果 rotten_time > i,则表示苹果还没有腐烂,可以吃掉。
-
eaten_apples += 1: 吃掉一个苹果,增加 eaten_apples 的计数。
-
if apple_count > 1:: 如果吃掉的苹果数量大于 1,则将剩余的苹果放回堆中,更新苹果数量为 apple_count - 1。
-
break: 吃掉一个苹果后,结束当前天的循环。
-
else: continue: 如果苹果已经腐烂,跳过当前苹果,继续从堆中取出下一个苹果。
-
else: pass: 如果堆为空,则当天没有苹果可以吃。
-
while heap:: 在遍历完 apples 数组后,可能堆中还有一些苹果没有腐烂。 继续从堆中取出苹果,直到堆为空。
-
if rotten_time > len(apples):: 检查苹果是否在遍历完 apples 数组后仍然没有腐烂。
-
return eaten_apples: 返回吃掉的苹果的最大数目。
时间复杂度: O(n log n),其中 n 是 apples 和 days 数组的长度。 这是因为我们使用了堆,堆的插入和删除操作的时间复杂度都是 O(log n)。
空间复杂度: O(n),因为堆最多可能存储 n 个苹果。
示例:
python
apples = [1, 2, 3, 5, 2]
days = [3, 2, 1, 4, 2]
solution = Solution()
result = solution.eatenApples(apples, days)
print(result) # 输出 7