|
| 1 | +/** |
| 2 | + * 1751. Maximum Number of Events That Can Be Attended II |
| 3 | + * https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended-ii/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an array of events where events[i] = [startDayi, endDayi, valuei]. The ith event |
| 7 | + * starts at startDayi and ends at endDayi, and if you attend this event, you will receive a value |
| 8 | + * of valuei. You are also given an integer k which represents the maximum number of events you can |
| 9 | + * attend. |
| 10 | + * |
| 11 | + * You can only attend one event at a time. If you choose to attend an event, you must attend the |
| 12 | + * entire event. Note that the end day is inclusive: that is, you cannot attend two events where |
| 13 | + * one of them starts and the other ends on the same day. |
| 14 | + * |
| 15 | + * Return the maximum sum of values that you can receive by attending events. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {number[][]} events |
| 20 | + * @param {number} k |
| 21 | + * @return {number} |
| 22 | + */ |
| 23 | +var maxValue = function(events, k) { |
| 24 | + events.sort((a, b) => a[0] - b[0]); |
| 25 | + const n = events.length; |
| 26 | + const dp = Array.from({ length: k + 1 }, () => new Array(n + 1).fill(-1)); |
| 27 | + |
| 28 | + return maximize(0, k); |
| 29 | + |
| 30 | + function findNext(index, end) { |
| 31 | + let left = index; |
| 32 | + let right = n; |
| 33 | + while (left < right) { |
| 34 | + const mid = Math.floor((left + right) / 2); |
| 35 | + if (events[mid][0] > end) { |
| 36 | + right = mid; |
| 37 | + } else { |
| 38 | + left = mid + 1; |
| 39 | + } |
| 40 | + } |
| 41 | + return left; |
| 42 | + } |
| 43 | + |
| 44 | + function maximize(index, remaining) { |
| 45 | + if (index >= n || remaining === 0) return 0; |
| 46 | + if (dp[remaining][index] !== -1) return dp[remaining][index]; |
| 47 | + |
| 48 | + const nextIndex = findNext(index + 1, events[index][1]); |
| 49 | + const take = events[index][2] + maximize(nextIndex, remaining - 1); |
| 50 | + const skip = maximize(index + 1, remaining); |
| 51 | + |
| 52 | + return dp[remaining][index] = Math.max(take, skip); |
| 53 | + } |
| 54 | +}; |
0 commit comments