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 Number of Events That Can Be Attended IIInput Events[1,2,4], [3,4,3], [2,3,1]k = 2Sort & DPSort by end timeChoose optimal eventsSelected Events[1,2,4] + [3,4,3]Value: 4 + 3 = 7Timeline visualization:Event 1[1,2,4]Event 3[2,3,1]Event 2[3,4,3]✓ Choose Events 1 & 2 (no overlap)✗ Skip Event 3 (overlaps with Event 1)🎯 Maximum Value: 7
Understanding the Visualization
1
Input
Events with [start, end, value] and limit k=2
2
Process
Sort by end time, use DP to find optimal selection
3
Output
Maximum value from selected events
Key Takeaway
🎯 Key Insight: Sort events by end time, then use dynamic programming to choose the optimal combination of non-overlapping events within the limit k.
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