#1751

Maximum Number of Events That Can Be Attended II

Hard
ArrayBinary SearchDynamic ProgrammingSortingDynamic ProgrammingBinary SearchGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * k * log(n))
Space
O(1)
O(n * k)
💡

Intuition

Time O(n * k * log(n))Space O(n * k)

The optimal approach uses dynamic programming combined with binary search to efficiently calculate the maximum value of attending events. By sorting the events and using a DP table, we can avoid redundant calculations and quickly find the best options.

⚙️

Algorithm

4 steps
  1. 1Step 1: Sort the events by their end day.
  2. 2Step 2: Initialize a DP table where dp[i][j] represents the maximum value obtainable by attending up to j events from the first i events.
  3. 3Step 3: For each event, decide whether to attend it or not. If attending, find the last non-overlapping event using binary search.
  4. 4Step 4: Update the DP table based on the choice made.
solution.py24 lines
1def maxValue(events, k):
2    events.sort(key=lambda x: x[1])
3    n = len(events)
4    dp = [[0] * (k + 1) for _ in range(n + 1)]
5
6    for i in range(1, n + 1):
7        for j in range(1, k + 1):
8            # Option 1: Don't attend the current event
9            dp[i][j] = dp[i - 1][j]
10            # Option 2: Attend the current event
11            last_non_overlap = binary_search(events, i - 1, events[i - 1][0])
12            dp[i][j] = max(dp[i][j], dp[last_non_overlap][j - 1] + events[i - 1][2])
13
14    return dp[n][k]
15
16def binary_search(events, right, start):
17    left = 0
18    while left <= right:
19        mid = (left + right) // 2
20        if events[mid][1] < start:
21            left = mid + 1
22        else:
23            right = mid - 1
24    return right

Complexity note: The time complexity is O(n * k * log(n)) because we iterate through n events and for each event, we perform a binary search, which takes log(n) time. The space complexity is O(n * k) due to the DP table.

  • 1Sorting events by their end day allows for efficient overlap checking.
  • 2Using dynamic programming helps to build solutions incrementally and avoid redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.