Maximum Number of Events That Can Be Attended II - Problem

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 & Output

Example 1 — Basic Case
$ Input: events = [[1,2,4],[3,4,3],[2,3,1]], k = 2
Output: 7
💡 Note: Choose events [1,2,4] and [3,4,3]. Event [1,2,4] ends at day 2 and [3,4,3] starts at day 3, so no overlap. Total value = 4 + 3 = 7.
Example 2 — Single Event
$ Input: events = [[1,2,4],[3,4,3],[2,3,1]], k = 1
Output: 4
💡 Note: Can only attend one event. Choose the highest value event [1,2,4] with value 4.
Example 3 — All Overlapping
$ Input: events = [[1,1,1],[2,2,2],[3,3,3]], k = 3
Output: 6
💡 Note: No events overlap since each lasts only one day. Can attend all three: 1 + 2 + 3 = 6.

Constraints

  • 1 ≤ events.length ≤ 106
  • events[i].length == 3
  • 1 ≤ startDayi ≤ endDayi ≤ 109
  • 1 ≤ valuei ≤ 106
  • 1 ≤ k ≤ min(events.length, 106)

Visualization

Tap to expand
Maximum Events That Can Be Attended II INPUT Events Timeline: Day 1 2 3 4 E1: v=4 E2: v=3 E3: v=1 Input Data events = [ [1,2,4], [3,4,3], [2,3,1] ] k = 2 [start, end, value] Max k=2 events allowed No overlapping events! ALGORITHM (DP) 1 Sort Events Sort by end day ascending 2 Define DP State dp[i][j] = max value using first i events, pick j events 3 Binary Search Find last non-overlapping event for each event i 4 Transition dp[i][j] = max(skip, take) DP Table (k=2) j=0 j=1 j=2 E1: 0 4 - E3: 0 4 - E2: 0 4 7 Sorted: E1--E3--E2 FINAL RESULT Optimal Selection: Event 1: [1,2,4] Days 1-2, Value = 4 Event 2: [3,4,3] Days 3-4, Value = 3 Event 3 [2,3,1] skipped Overlaps + low value Total Value = 4 + 3 = 7 Output: 7 Maximum Value Key Insight: This is a weighted interval scheduling problem. We use DP with binary search optimization. For each event, we decide: skip it (keep previous best) or take it (add its value to best non-overlapping solution with j-1 events). Time: O(n*k*log n), Space: O(n*k) TutorialsPoint - Maximum Number of Events That Can Be Attended II | DP Approach
Asked in
Google 15 Facebook 12 Amazon 10
89.4K Views
Medium Frequency
~35 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen