Maximum Number of Events That Can Be Attended II (LeetCode 1751): Solution and Explanation

Hard
Array
Binary Search
Dynamic Programming
Sorting

Each event has a start day, an end day and a value. You may attend at most k events, and an event you attend must be attended in full, so no two chosen events can share a day. Maximize the total value of the events you attend.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Without the limit k this would be weighted interval scheduling: sort the events, and for each one decide to take it or skip it, jumping past everything that overlaps when you take it. The cap on the number of events adds one more dimension to the state, the number of events still allowed, but the shape of the decision stays the same.

Sort events by start day and define dp(i, remaining) as the best total using events from index i onward with at most remaining picks left. If we skip event i, the answer is dp(i + 1, remaining). If we take it, we earn its value, use one pick and must continue from the first event that starts strictly after event i ends, which is dp(next, remaining - 1). Any event between i and next starts on or before event i's last day, so it overlaps.

Because the events are sorted by start day, next is found with binary search for the first start greater than end. Note the strict inequality: an event ending on day 3 and another starting on day 3 share that day, so they conflict. Memoization ensures each of the n × k states is computed once, and each one does a single O(log n) binary search, which comfortably handles the constraint that n × k is at most 10^6.

Approach: Memoized take-or-skip DP with binary search

  1. Sort events by start day.
  2. Define dp(i, remaining), returning 0 when i >= n or remaining == 0.
  3. Binary search over indices i + 1 to n for the first event whose start is strictly greater than events[i][1], and call it lo.
  4. Compute take = events[i][2] + dp(lo, remaining - 1).
  5. Compute skip = dp(i + 1, remaining) and return the larger of the two.
  6. Return dp(0, k), with results cached by lru_cache.

Step-by-step example

events = [[1,2,4], [3,4,3], [2,3,1]], k = 2
  1. After sorting by start, the events are [1,2,4], [2,3,1], [3,4,3].
  2. dp(0, 2): event [1,2,4] ends on day 2, and the first event starting after day 2 is index 2. Taking it gives 4 + dp(2, 1).
  3. dp(2, 1): taking [3,4,3] gives 3 + dp(3, 0) = 3, skipping gives 0, so it returns 3. The take branch at index 0 is therefore 7.
  4. The skip branch dp(1, 2) takes [2,3,1] for 1 + dp(3, 1) = 1, or skips to dp(2, 2) = 3, so it returns 3.
  5. dp(0, 2) = max(7, 3) = 7, from attending [1,2,4] and [3,4,3].

Code: Python, Java, C++

1class Solution:
2    def maxValue(self, events: List[List[int]], k: int) -> int:
3        events.sort()
4        n = len(events)
5
6        @lru_cache(maxsize=None)
7        def dp(i, remaining):
8            if i >= n or remaining == 0:
9                return 0
10
11            # Binary search for next event after current ends
12            end = events[i][1]
13            lo, hi = i + 1, n
14            while lo < hi:
15                mid = (lo + hi) // 2
16                if events[mid][0] > end:
17                    hi = mid
18                else:
19                    lo = mid + 1
20
21            # Take or skip current event
22            take = events[i][2] + dp(lo, remaining - 1)
23            skip = dp(i + 1, remaining)
24            return max(take, skip)
25
26        return dp(0, k)

Time and space complexity

Time

O(n log n + n × k × log n)

Sorting costs O(n log n). There are n × k memoized states and each runs one O(log n) binary search.

Space

O(n × k)

The memo cache stores one value per (i, remaining) pair, and the recursion depth is at most n.

Other approaches

Bottom-up DP with precomputed next indices (time O(n log n + n × k), space O(n × k))

Compute next[i] once for every event with binary search, then fill a table dp[i][j] from the last event backward for each j from 1 to k. It removes recursion and repeated searches, and only two columns are needed at a time if memory is tight.

Common mistakes

  • Searching for a start greater than or equal to the end day. Events here include both endpoints, so the next event must start strictly after the end.
  • Sorting by end day while searching by start day, which breaks the binary search because starts are no longer sorted.
  • Hitting Python's recursion limit for large n. Either raise the limit or switch to the bottom-up table.
  • Treating the problem as the unlimited version and ignoring k, which can pick more events than allowed.

Frequently asked questions

How is this different from Maximum Profit in Job Scheduling?

The structure is the same weighted interval scheduling DP. This problem adds a cap of k events, which becomes a second DP dimension, and it treats shared end and start days as overlapping.

Why is binary search needed?

After taking event i, we jump to the first event that starts after it ends. Since events are sorted by start day, binary search finds that index in O(log n) instead of scanning.

Why does the DP fit in time when k can be large?

The constraints guarantee that k × n is at most 10^6, so the number of states stays bounded no matter how the two values are split.