Skip to content

Commit 97a9d6f

Browse files
authored
Create 2106-maximum-fruits-harvested-after-at-most-k-steps.js
1 parent df9998d commit 97a9d6f

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/**
2+
* @param {number[][]} fruits
3+
* @param {number} startPos
4+
* @param {number} k
5+
* @return {number}
6+
*/
7+
const maxTotalFruits = function(fruits, startPos, k) {
8+
let n = fruits.length, { max, min } = Math
9+
let pos = fruits.map(([p,a]) => p)
10+
const prefix = Array(n).fill(0)
11+
12+
let curr = 0
13+
for (let i = 0; i < n; i++) {
14+
curr += fruits[i][1]
15+
prefix[i] = curr
16+
}
17+
18+
function bisect_left(a, x, lo = 0, hi = null) {
19+
// >= lower_bound
20+
if (lo < 0) throw new Error('lo must be non-negative')
21+
if (hi == null) hi = a.length
22+
while (lo < hi) {
23+
let mid = parseInt((lo + hi) / 2)
24+
a[mid] < x ? (lo = mid + 1) : (hi = mid)
25+
}
26+
return lo
27+
}
28+
function bisect_right(a, x, lo = 0, hi = null) {
29+
// > upper_bound
30+
if (lo < 0) throw new Error('lo must be non-negative')
31+
if (hi == null) hi = a.length
32+
while (lo < hi) {
33+
let mid = parseInt((lo + hi) / 2)
34+
x < a[mid] ? (hi = mid) : (lo = mid + 1)
35+
}
36+
return lo
37+
}
38+
function query(left, right) {
39+
left = max(left, 0)
40+
right = min(right, 200000)
41+
let l = bisect_left(pos, left)
42+
let r = bisect_right(pos, right) - 1
43+
if (l > r) return 0
44+
if (!l) return prefix[r]
45+
return prefix[r] - prefix[l - 1]
46+
}
47+
48+
49+
let best = 0
50+
let idx = 0
51+
for(let right = startPos + k; right > startPos - 1; right -= 2) {
52+
let cand = query(startPos - idx, right)
53+
best = max(best, cand)
54+
idx += 1
55+
}
56+
57+
idx = 0
58+
for(let left = startPos - k; left < startPos + 1; left += 2) {
59+
let cand = query(left, startPos + idx)
60+
best = max(best, cand)
61+
idx += 1
62+
}
63+
64+
return best
65+
};
66+

0 commit comments

Comments
 (0)