Skip to content

Commit d275406

Browse files
authored
Create 1235-maximum-profit-in-job-scheduling.js
1 parent 7871e59 commit d275406

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* @param {number[]} startTime
3+
* @param {number[]} endTime
4+
* @param {number[]} profit
5+
* @return {number}
6+
*/
7+
const jobScheduling = function (startTime, endTime, profit) {
8+
const items = Array.from({ length: startTime.length }, () => Array(3).fill(0))
9+
for (let i = 0; i < startTime.length; i++) {
10+
items[i] = [startTime[i], endTime[i], profit[i]]
11+
}
12+
items.sort((a1, a2) => a1[1] - a2[1])
13+
const dpEndTime = []
14+
const dpProfit = []
15+
dpEndTime.push(0)
16+
dpProfit.push(0)
17+
for (let item of items) {
18+
const s = item[0],
19+
e = item[1],
20+
p = item[2]
21+
let prevIdx = binarySearch(dpEndTime, 0, dpEndTime.length - 1, s + 1)
22+
if (prevIdx < 0) {
23+
prevIdx = -prevIdx - 1
24+
}
25+
prevIdx--
26+
const currProfit = dpProfit[prevIdx] + p,
27+
maxProfit = dpProfit[dpProfit.length - 1]
28+
if (currProfit > maxProfit) {
29+
dpProfit.push(currProfit)
30+
dpEndTime.push(e)
31+
}
32+
}
33+
return dpProfit[dpProfit.length - 1]
34+
}
35+
36+
function binarySearch(arr, l, r, x) {
37+
while (l <= r) {
38+
const m = l + ((r - l) >> 1)
39+
if (arr[m] === x) return m
40+
if (arr[m] < x) l = m + 1
41+
else r = m - 1
42+
}
43+
return -l - 1
44+
}

0 commit comments

Comments
 (0)