forked from TheAlgorithms/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWeightedIntervalScheduling.js
More file actions
68 lines (54 loc) · 1.47 KB
/
WeightedIntervalScheduling.js
File metadata and controls
68 lines (54 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* Solves the Weighted Interval Scheduling problem.
*
* Given intervals with start time, end time, and profit,
* returns the maximum profit such that no intervals overlap.
*
* Uses Dynamic Programming + Binary Search.
*
* Time Complexity: O(n log n)
* Space Complexity: O(n)
*
* @param {{start:number, end:number, profit:number}[]} intervals
* @returns {number}
*/
const weightedIntervalScheduling = (intervals) => {
if (!Array.isArray(intervals)) {
throw new Error('Input must be an array of intervals')
}
if (intervals.length === 0) return 0
intervals.sort((a, b) => a.end - b.end)
const n = intervals.length
const dp = Array(n).fill(0)
dp[0] = intervals[0].profit
const findLastNonOverlapping = (index) => {
let left = 0
let right = index - 1
while (left <= right) {
const mid = Math.floor((left + right) / 2)
if (intervals[mid].end <= intervals[index].start) {
if (
mid + 1 <= right &&
intervals[mid + 1].end <= intervals[index].start
) {
left = mid + 1
} else {
return mid
}
} else {
right = mid - 1
}
}
return -1
}
for (let i = 1; i < n; i++) {
let includeProfit = intervals[i].profit
const lastIndex = findLastNonOverlapping(i)
if (lastIndex !== -1) {
includeProfit += dp[lastIndex]
}
dp[i] = Math.max(dp[i - 1], includeProfit)
}
return dp[n - 1]
}
export { weightedIntervalScheduling }