Skip to content

Commit be167e9

Browse files
authored
Create 1705-maximum-number-of-eaten-apples.js
1 parent 9a1c531 commit be167e9

File tree

1 file changed

+100
-0
lines changed

1 file changed

+100
-0
lines changed
+100
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
/**
2+
* @param {number[]} apples
3+
* @param {number[]} days
4+
* @return {number}
5+
*/
6+
const eatenApples = function(apples, days) {
7+
8+
let ans = 0, n = apples.length;
9+
const que = new PriorityQueue();
10+
for (let i = 0; i < n; i++) {
11+
while (!que.isEmpty() && que.peek().exp <= i) que.pop();
12+
if (que.isEmpty()) {
13+
if (apples[i] == 0 && days[i] == 0) continue;
14+
}
15+
que.push({cnt: apples[i], exp: i + days[i]});
16+
ans++;
17+
let temp = que.peek();
18+
que.pop();
19+
if (--temp.cnt) que.push(temp);
20+
}
21+
let day = n;
22+
while (!que.isEmpty()) {
23+
while (!que.isEmpty() && que.peek().exp <= n) que.pop();
24+
if (que.isEmpty()) break;
25+
ans++;
26+
n++;
27+
let temp = que.peek();
28+
que.pop();
29+
if (--temp.cnt) que.push(temp);
30+
}
31+
return ans;
32+
};
33+
34+
class PriorityQueue {
35+
constructor(comparator = (a, b) => a.exp < b.exp) {
36+
this.heap = []
37+
this.top = 0
38+
this.comparator = comparator
39+
}
40+
size() {
41+
return this.heap.length
42+
}
43+
isEmpty() {
44+
return this.size() === 0
45+
}
46+
peek() {
47+
return this.heap[this.top]
48+
}
49+
push(...values) {
50+
values.forEach((value) => {
51+
this.heap.push(value)
52+
this.siftUp()
53+
})
54+
return this.size()
55+
}
56+
pop() {
57+
const poppedValue = this.peek()
58+
const bottom = this.size() - 1
59+
if (bottom > this.top) {
60+
this.swap(this.top, bottom)
61+
}
62+
this.heap.pop()
63+
this.siftDown()
64+
return poppedValue
65+
}
66+
replace(value) {
67+
const replacedValue = this.peek()
68+
this.heap[this.top] = value
69+
this.siftDown()
70+
return replacedValue
71+
}
72+
73+
parent = (i) => ((i + 1) >>> 1) - 1
74+
left = (i) => (i << 1) + 1
75+
right = (i) => (i + 1) << 1
76+
greater = (i, j) => this.comparator(this.heap[i], this.heap[j])
77+
swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])
78+
siftUp = () => {
79+
let node = this.size() - 1
80+
while (node > this.top && this.greater(node, this.parent(node))) {
81+
this.swap(node, this.parent(node))
82+
node = this.parent(node)
83+
}
84+
}
85+
siftDown = () => {
86+
let node = this.top
87+
while (
88+
(this.left(node) < this.size() && this.greater(this.left(node), node)) ||
89+
(this.right(node) < this.size() && this.greater(this.right(node), node))
90+
) {
91+
let maxChild =
92+
this.right(node) < this.size() &&
93+
this.greater(this.right(node), this.left(node))
94+
? this.right(node)
95+
: this.left(node)
96+
this.swap(node, maxChild)
97+
node = maxChild
98+
}
99+
}
100+
}

0 commit comments

Comments
 (0)