You are given an array of events where events[i] = [startDayi, endDayi, valuei]. The ith event starts at startDayi and ends at endDayi, and if you attend this event, you will receive a value of valuei. 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.
Input:
events =[[1,2,4],[3,4,3],[2,3,1]], k =2Output:
7Explanation: Choose the green events,0 and 1(0-indexed)for a total value of 4+3=7.
Example 2:
1
2
3
4
5
6
Input:
events =[[1,2,4],[3,4,3],[2,3,10]], k =2Output:
10Explanation: Choose event 2for 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:
1
2
3
4
5
Input:
events =[[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k =3Output:
9Explanation: Although the events do not overlap, you can only attend 3 events. Pick the highest valued three.
We want to select up to k non-overlapping events to maximize the total value. For each event, we can either attend it (if it doesn’t overlap with the previous attended event) or skip it. We use dynamic programming with memoization to efficiently explore all possibilities.
There are n events and up to k choices for each event. The DP table has n*k states, and each state is computed once due to memoization. Sorting the events takes O(n log n), but the DP dominates.
For each DP state, we either skip or attend the event, so the recursion is bounded by the DP table size.
🧺 Space complexity:O(n*k)
The DP table stores results for each event and each possible remaining slot, resulting in n*k entries. The recursion stack is at most O(n) deep, but the DP table is the main space cost.