题目描述
有一棵特殊的苹果树,一连 n 天,每天都可以长出若干个苹果。在第 i 天,树上会长出 apples[i] 个苹果,这些苹果将会在 days[i] 天后(也就是说,第 i + days[i] 天时)腐烂,变得无法食用。也可能有那么几天,树上不会长出新的苹果,此时用 apples[i] == 0 且 days[i] == 0 表示。
你打算每天 最多 吃一个苹果来保证营养均衡。注意,你可以在这 n 天之后继续吃苹果。
给你两个长度为 n 的整数数组 days 和 apples ,返回你可以吃掉的苹果的最大数目。
输入
apples = [1,2,3,5,2], days = [3,2,1,4,2]
输出
7
解释:你可以吃掉 7 个苹果:
- 第一天,你吃掉第一天长出来的苹果。
- 第二天,你吃掉一个第二天长出来的苹果。
- 第三天,你吃掉一个第二天长出来的苹果。过了这一天,第三天长出来的苹果就已经腐烂了。
- 第四天到第七天,你吃的都是第四天长出来的苹果。
输入
apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2]
输出
5
解释:你可以吃掉 5 个苹果:
- 第一天到第三天,你吃的都是第一天长出来的苹果。
- 第四天和第五天不吃苹果。
- 第六天和第七天,你吃的都是第六天长出来的苹果。
解题思路
贪心算法,每次选择即将过期的苹果,这样可以保证后面过期的苹果在下一天可以选择。如果选择后面过期的苹果吃,那么即将过期的苹果在下一天肯定过期了,白白浪费掉一个后面才过期的苹果。
维护苹果的数量和过期时间,数据结构采用一个小顶堆的优先队列
参考代码
package LeetCodeWeeklyContest;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;
public class LC02 {
int MAX_N = (int) 4e4;
int[] apples;
int[] days;
class Node {
int num;
int time;
Node(int x, int y) {
this.num = x;
this.time = y;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] s1 = sc.nextLine().split(",");
String[] s2 = sc.nextLine().split(",");
int n = s1.length;
LC02 ins = new LC02();
ins.apples = new int[n];
ins.days = new int[n];
for (int i = 0; i < n; i++) ins.apples[i] = Integer.parseInt(s1[i]);
for (int i = 0; i < n; i++) ins.days[i] = Integer.parseInt(s2[i]);
int ans = ins.solve(n);
System.out.println(ans);
sc.close();
}
private int solve(int n) {
PriorityQueue<Node> que = new PriorityQueue<>(new Comparator<Node>(){
@Override
public int compare(Node o1, Node o2) {
// TODO Auto-generated method stub
return o1.time - o2.time;
}
});
int ans = 0;
for (int i = 0; i < MAX_N; i++) {
if (i < n && apples[i] != 0 ) que.add(new Node(apples[i], i + days[i] - 1));
while (!que.isEmpty() && que.peek().time < i) que.poll();
if (!que.isEmpty()) {
Node tmp = que.poll();
int num = tmp.num - 1;
int time = tmp.time;
ans++;
if (num > 0) que.add(new Node(num, time));
}
}
return ans;
}
}