Taro Logo

Maximum Number of Events That Can Be Attended II

#203 Most AskedHard
Topics:
Dynamic Programming

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.

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.length
  • 1 <= k * events.length <= 106
  • 1 <= startDayi <= endDayi <= 109
  • 1 <= valuei <= 106

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Are the start and end days inclusive, meaning an event ending on day $X$ allows us to attend another event starting on day $X + 1$, or must it be $X + 2$?
  2. What is the maximum possible value for the start day, end day, and the event values?
  3. Can the event values or the maximum number of events to attend be negative or zero?
  4. If no events can be attended (e.g., $k = 0$ or empty input), should the function return 0?
  5. Can the input array of events contain exact duplicates with the exact same start day, end day, and value?

Brute Force Solution

Approach

Imagine you have a calendar full of events with different start times, end times, and values, and you want to pick a combination that gives you the highest total value without overlapping. The brute force approach involves exploring every single combination of events you could possibly attend to see which one pays off the most.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first event on your schedule.
  2. Decide whether to attend this first event or skip it entirely.
  3. If you decide to attend it, cross off any other events that happen at the same time because you cannot be in two places at once.
  4. Move on to the next available event and repeat the process of choosing whether to attend it or skip it, making sure you never exceed your maximum allowed number of events.
  5. Keep making these choices for every single event on your list until you have explored a complete path from the beginning to the end of your calendar.
  6. Write down the total value you collected along this specific path of chosen events.
  7. Go back and repeat this entire process for every other possible path of decisions you could have made.
  8. Compare the total values from every single path you explored and pick the one that gives you the highest total value.

Code Implementation

class Solution:
    def maxValue(self, events: list[list[int]], maximum_events: int) -> int:
        sorted_events = sorted(events, key=lambda event_item: event_item[0])
        total_event_count = len(sorted_events)
        
        def explore_schedules(current_index: int, remaining_events: int) -> int:
            # If we exhausted events or limits, no more value can be added to our schedule
            if current_index >= total_event_count or remaining_events == 0:
                return 0
            
            skip_current_value = explore_schedules(current_index + 1, remaining_events)
            
            next_valid_index = current_index + 1
            while next_valid_index < total_event_count:
                if sorted_events[next_valid_index][0] > sorted_events[current_index][1]:
                    break
                next_valid_index += 1
            
            # Attend current event and search for the next compatible one to maximize value
            attend_current_value = sorted_events[current_index][2] + explore_schedules(next_valid_index, remaining_events - 1)
            
            return max(skip_current_value, attend_current_value)
            
        return explore_schedules(0, maximum_events)

Big(O) Analysis

Time Complexity
O(n * k * log n) – To solve this, we first sort the n events by their start times, which takes O(n log n) time. Then, we use dynamic programming with memoization where we make choices for each of the n events across up to k allowed attendances. For each event, finding the next available non-overlapping event using binary search adds a log n factor. Multiplying the n events by the k attendance limit and the log n binary search cost yields n * k * log n operations, which simplifies to O(n * k * log n).
Space Complexity
O(N * K) – The auxiliary space is primarily driven by a dynamic programming memoization table and the recursion stack, where N represents the number of events and K represents the maximum number of events that can be attended. Specifically, the memoization table requires a two-dimensional structure of size N by K to store intermediate results for overlapping subproblems. Additionally, sorting the events and executing recursive exploration paths contribute auxiliary stack frames up to a depth proportional to N. Simplifying these contributions yields an overall space complexity of Big O of N times K.

Optimal Solution

Approach

To find the most valuable combination of events without overlapping, we can sort the events by their starting times and make smart choices using dynamic planning and binary search. Instead of blindly testing every possible combination, we evaluate whether to attend or skip each event while remembering the best outcomes we have already calculated.

Here's how the algorithm would work step-by-step:

  1. Sort all the available events in order of their start times so we can process them chronologically.
  2. Imagine making a decision for every single event: we either choose to attend it or we skip it to look for something better.
  3. If we decide to attend a particular event, we collect its value and immediately jump forward in time to the next available event that starts after our current event finishes.
  4. If we skip the current event, we simply move on to examine the very next event in line.
  5. To make this search for the next valid event lightning fast, use a shortcut technique to instantly find the first event that starts after the current one ends, rather than scanning one by one.
  6. Keep track of the maximum value we can accumulate at each step and how many total events we are still allowed to attend, ensuring we never exceed our maximum allowed event count.
  7. Combine these choices so that whenever we overlap or run out of allowed events, we stop, and ultimately the strategy reveals the highest possible total value we can achieve.

Code Implementation

import bisect

class Solution:
    def maxValue(self, events: list[list[int]], max_events_allowed: int) -> int:
        events.sort(key=lambda event_item: event_item[0])
        
        total_event_count = len(events)
        start_times_list = [event_item[0] for event_item in events]
        memoization_table = [[-1] * (max_events_allowed + 1) for _ in range(total_event_count)]

        def compute_maximum_value(current_index, remaining_events):
            if current_index >= total_event_count or remaining_events == 0:
                return 0
            
            if memoization_table[current_index][remaining_events] != -1:
                return memoization_table[current_index][remaining_events]
            
            # Skipping the current event allows us to evaluate the next chronological option.
            skip_current_value = compute_maximum_value(current_index + 1, remaining_events)
            
            next_valid_index = bisect.bisect_right(start_times_list, events[current_index][1])
            
            # Attending the current event yields value and jumps straight to the next non-overlapping event.
            attend_current_value = events[current_index][2] + compute_maximum_value(next_valid_index, remaining_events - 1)
            
            memoization_table[current_index][remaining_events] = max(skip_current_value, attend_current_value)
            return memoization_table[current_index][remaining_events]

        # We begin our evaluation from the very first event with our full allowed budget.
        return compute_maximum_value(0, max_events_allowed)

Big(O) Analysis

Time Complexity
O(n log n * k) – To break down the time complexity, let n be the number of events and k be the maximum number of events we are allowed to attend. First, sorting the events by their start times takes O(n log n) time. Then, our dynamic programming state space consists of n events multiplied by k allowed choices, resulting in n times k states to evaluate. For each state, we make a constant-time choice to attend or skip, using binary search to find the next valid event in O(log n) time. Combining the states and the binary search gives a total operation count of n times k times log n, which simplifies to the Big O notation of O(n log n * k).
Space Complexity
O(N * K) – The auxiliary space is primarily driven by the dynamic programming memoization table, which stores the maximum value for every combination of the event index from 0 to N and the remaining allowed events from 0 to K. Additionally, sorting the N events and utilizing the recursive call stack both require extra space proportional to N in the worst-case scenario. Therefore, combining the two-dimensional table of size N times K with the recursion stack and sorting overhead results in a total auxiliary space complexity of O(N times K).

Edge Cases

Maximum allowed events $k$ is greater than or equal to the total number of events
How to Handle:
We simply cap $k$ at the total number of events or let the recursive state naturally terminate when all events are processed.
All events overlap with each other
How to Handle:
The algorithm correctly evaluates each overlapping event individually and returns the maximum single event value up to $k=1$.
Events have identical start and end days but different values
How to Handle:
Sorting by start day preserves all of them, and the dp state evaluates each independently to pick the highest value.
Extreme boundary values for start day, end day, and event values
How to Handle:
Using standard 64-bit integers for value sums prevents arithmetic overflow during accumulation.
Single event provided in the input array with $k=1$
How to Handle:
The algorithm processes the single element and returns its value without triggering out-of-bounds errors.
Deep recursion stack when $k$ is large and events are numerous
How to Handle:
Using bottom-up dynamic programming or memoized top-down recursion with binary search avoids stack overflow and redundant subproblem evaluations.
Binary search for the next non-overlapping event yields no valid subsequent events
How to Handle:
The search function safely returns an index out of bounds, which terminates the branching condition for future event choices.
0/245 completed