|
| 1 | +/** |
| 2 | + * 2054. Two Best Non-Overlapping Events |
| 3 | + * https://leetcode.com/problems/two-best-non-overlapping-events/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given a 0-indexed 2D integer array of events where |
| 7 | + * events[i] = [startTimei, endTimei, valuei]. The ith event starts at |
| 8 | + * startTimei and ends at endTimei, and if you attend this event, you will |
| 9 | + * receive a value of valuei. You can choose at most two non-overlapping |
| 10 | + * events to attend such that the sum of their values is maximized. |
| 11 | + * |
| 12 | + * Return this maximum sum. |
| 13 | + * |
| 14 | + * Note that the start time and end time is inclusive: that is, you cannot |
| 15 | + * attend two events where one of them starts and the other ends at the |
| 16 | + * same time. More specifically, if you attend an event with end time t, |
| 17 | + * the next event must start at or after t + 1. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {number[][]} events |
| 22 | + * @return {number} |
| 23 | + */ |
| 24 | +var maxTwoEvents = function(events) { |
| 25 | + events.sort((a, b) => a[1] - b[1]); |
| 26 | + |
| 27 | + const maxValueUpTo = new Array(events.length); |
| 28 | + maxValueUpTo[0] = events[0][2]; |
| 29 | + |
| 30 | + for (let i = 1; i < events.length; i++) { |
| 31 | + maxValueUpTo[i] = Math.max(maxValueUpTo[i - 1], events[i][2]); |
| 32 | + } |
| 33 | + |
| 34 | + let result = 0; |
| 35 | + for (let i = 0; i < events.length; i++) { |
| 36 | + const [start, end, value] = events[i]; |
| 37 | + result = Math.max(result, value); |
| 38 | + |
| 39 | + let left = 0; |
| 40 | + let right = i - 1; |
| 41 | + let bestIndex = -1; |
| 42 | + while (left <= right) { |
| 43 | + const mid = Math.floor((left + right) / 2); |
| 44 | + if (events[mid][1] < start) { |
| 45 | + bestIndex = mid; |
| 46 | + left = mid + 1; |
| 47 | + } else { |
| 48 | + right = mid - 1; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + if (bestIndex !== -1) { |
| 53 | + result = Math.max(result, value + maxValueUpTo[bestIndex]); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + return result; |
| 58 | +}; |
0 commit comments