- 1705.吃苹果的最大数目
- 题目描述
- 思路
- 贪心+优先队列
- Java实现
- Python实现
1705.吃苹果的最大数目 题目描述
吃苹果的最大数目
思路 贪心+优先队列
为了将吃苹果的数目最大化,应该用贪心策略,在尚未腐烂的苹果中选择腐烂日期最近的苹果吃掉。
为了得到腐烂日期最近的苹果,可以使用优先队列存储每个苹果的腐烂日期,优先队列中最小的元素会最先被取出。
计算吃苹果的最大数目可以分为两个阶段计算,第一阶段是第0天到第n-1天,即天数在数组下标范围内,第二阶段是第n天及以后,即天数在数组下标范围外。
class Solution {
public int eatenApples(int[] apples, int[] days) {
int ans = 0;
PriorityQueue pq = new PriorityQueue((a, b) -> a[0] - b[0]);
int n = apples.length;
int i = 0;
while (i < n) {
while (!pq.isEmpty() && pq.peek()[0] <= i) {
pq.poll();
}
int rottenDay = i + days[i];
int count = apples[i];
if (count > 0) {
pq.offer(new int[]{rottenDay, count});
}
if (!pq.isEmpty()) {
int[] arr = pq.peek();
arr[1]--;
if (arr[1] == 0) {
pq.poll();
}
ans++;
}
i++;
}
while (!pq.isEmpty()) {
while (!pq.isEmpty() && pq.peek()[0] <= i) {
pq.poll();
}
if (pq.isEmpty()) {
break;
}
int[] arr = pq.poll();
int curr = Math.min(arr[0] - i, arr[1]);
ans += curr;
i += curr;
}
return ans;
}
}
Python实现
class Solution:
def eatenApples(self, apples: List[int], days: List[int]) -> int:
ans = 0
pq = []
i = 0
while i < len(apples):
while pq and pq[0][0] <= i:
heappop(pq)
if apples[i]:
heappush(pq, [i + days[i], apples[i]])
if pq:
pq[0][1] -= 1
if pq[0][1] == 0:
heappop(pq)
ans += 1
i += 1
while pq:
while pq and pq[0][0] <= i:
heappop(pq)
if len(pq) == 0:
break
p = heappop(pq)
num = min(p[0] - i, p[1])
ans += num
i += num
return ans



