Skip to main content
  1. Posts/

LeetCode-1705 吃苹果的最大数目

·1 min·

LeetCode-1705 吃苹果的最大数目 #

Solution 1 #

贪心, 优先吃保质期短的, 用最小堆来维护.

代码如下:

class Solution:
    def eatenApples(self, apples: List[int], days: List[int]) -> int:
        h = []
        ans = i = 0
        while i < 10 ** 5:
            if i < len(apples):
                heappush(h, [i + days[i] - 1, apples[i]])
            while h and h[0][0] < i:
                heappop(h)
            if h:
                ans += 1
                x = heappop(h)
                x[1] -= 1
                if x[1] > 0:
                    heappush(h, x)
            else:
                if i >= len(apples):
                    return ans
            i += 1
        return ans