Maximum Number of Events That Can Be Attended II Problem
Description
LeetCode Problem 1751.
You are given an array of events where events[i] = [startDay_i, endDay_i, value_i]. The i^th event starts at startDay_iand ends at endDay_i, and if you attend this event, you will receive a value of value_i. You are also given an integer k which represents the maximum number of events you can attend.
You can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day is inclusive: that is, you cannot attend two events where one of them starts and the other ends on the same day.
Return the maximum sum of values that you can receive by attending events.
Example 1:

Input: events = [[1,2,4],[3,4,3],[2,3,1]], k = 2
Output: 7
Explanation: Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7.
Example 2:

Input: events = [[1,2,4],[3,4,3],[2,3,10]], k = 2
Output: 10
Explanation: Choose event 2 for a total value of 10.
Notice that you cannot attend any other event as they overlap, and that you do not have to attend k events.
Example 3:

Input: events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3
Output: 9
Explanation: Although the events do not overlap, you can only attend 3 events. Pick the highest valued three.
Constraints:
1 <= k <= events.length1 <= k * events.length <= 10^61 <= startDay_i <= endDay_i <= 10^91 <= value_i <= 10^6
Solution
Approach: Sort, Memoised Recursion and Binary Search
Sort the events by start day. Let dfs(i, k) be the best total value when we may still attend at most k events, choosing among events i, i + 1, ... The answer is dfs(0, k).
For event i there are two choices:
- Skip it:
dfs(i + 1, k). - Attend it: we gain
value[i], and the next event we can attend must start after dayend[i]. Because events are sorted by start, a binary search finds the first such eventj. This choice is worthvalue[i] + dfs(j, k - 1).
Take the larger of the two, and cache the result for each pair (i, k) so that it is computed once.
Complexity: O(n log n + nk) time (the sort, plus n * k states each with an O(log n) binary search that can be done once per event) and O(nk) space for the cache.
from bisect import bisect_right
from functools import lru_cache
class Solution:
def maxValue(self, events: List[List[int]], k: int) -> int:
events.sort()
starts = [e[0] for e in events]
@lru_cache(None)
def dfs(i: int, k: int) -> int:
if i >= len(events):
return 0
_, ed, val = events[i]
ans = dfs(i + 1, k)
if k:
j = bisect_right(starts, ed, i + 1)
ans = max(ans, dfs(j, k - 1) + val)
return ans
return dfs(0, k)