Python 1751.py
class Solution:
def maxValue(self, events: List[List[int]], k: int) -> int:
events.sort()
@cache
def deeper(pos, attended):
if pos == len(events) or attended == k:
return 0
start, end, value = events[pos]
# attend
next = bisect_left(events, [ end + 1, 0, 0 ])
best = value + deeper(next, attended + 1)
# or skip
best = max(best, deeper(pos + 1, attended))
return best
return deeper(0, 0)
Difficulty
and has an acceptance rate of about 64% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
- Dynamic Programming
- Sorting
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the problem of selecting up to k non-overlapping events to maximize the total value. It follows a classic dynamic programming approach with memoization, leveraging sorting and binary search to efficiently locate the next compatible event after attending the current one. The core logic is encapsulated in a recursive helper that explores the two possibilities at each event: attend it or skip it.
Key Steps
Sorting and Preparation
events.sort()
Before any computation, the list of events is sorted in ascending order of their start times (and subsequently by end time and value due to the tuple ordering). This ordering guarantees that when the algorithm scans the events sequentially, any later index corresponds to an event that starts no earlier than the current one. The sorted structure is essential for the binary search that follows.
Recursive Decision Function
@cache
def deeper(pos, attended):
if pos == len(events) or attended == k:
return 0
start, end, value = events[pos]
# attend
next = bisect_left(events, [ end + 1, 0, 0 ])
best = value + deeper(next, attended + 1)
# or skip
best = max(best, deeper(pos + 1, attended))
return best
The deeper function receives the current index pos and the count of events already attended attended. The base case returns zero when there are no more events to consider or the attendance limit k has been reached. For each event, the function extracts its start, end, and value, then evaluates two branches:
- Attending the event: it adds the event’s value to the optimal result of the sub-problem that starts at the first event whose start time is greater than the current event’s end.
- Skipping the event: it proceeds to the next index without increasing the attended count.
The maximum of these two branches is returned, and the @cache decorator ensures that identical sub-problems are computed only once.
Binary Search for Next Compatible Event
next = bisect_left(events, [ end + 1, 0, 0 ])
When an event is attended, the algorithm must find the earliest subsequent event that does not overlap. By searching for the insertion point of a synthetic event [end + 1, 0, 0], bisect_left returns the smallest index whose start time exceeds the current event’s end. This operation runs in logarithmic time and eliminates the need for a linear scan, preserving efficiency even for large input sizes.
Edge Cases Handled
The recursion terminates gracefully when the event list is exhausted, covering the scenario where the last event is processed and there are no further candidates. The condition attended == k prevents the algorithm from exceeding the allowed number of selections, correctly handling inputs where k is larger than the total number of non-overlapping events. The binary search uses end + 1 as the target start, ensuring that events that end exactly when another begins are considered non-overlapping, which aligns with the typical definition of event compatibility.
When multiple events share the same start time, the initial sorting places them in a deterministic order, and the binary search still finds the correct next index because it only depends on the start time component. The code also copes with an empty events list: the initial call to deeper(0, 0) immediately hits the base case and returns zero.
Performance Optimizations
Memoization via the @cache decorator eliminates redundant calculations by storing the result of each (pos, attended) pair. This dramatically reduces the number of recursive calls from exponential to polynomial in the number of events and the limit k. The sorted arrangement of events combined with binary search provides a fast way to jump to the next feasible event, avoiding a linear scan that would otherwise dominate the runtime. Together, these techniques ensure that the algorithm scales well for inputs with thousands of events and moderate values of k.
ELI5 - Simplified Explanation
Imagine you have a big pile of fun activities to choose from, like going to a puppet show, a park visit, or a craft workshop. Each activity happens at a specific time and gives you a certain amount of happiness points. You want to pick the best activities to collect as many points as you can, but there is one rule: you only have a limited amount of time to spend, and you cannot join two things if they happen at the same time.
First, the code lines up all the activities in order by their start times to make them easier to look at. Then, there is a clever little helper that looks at each activity one by one. For every choice, there are two paths. One path is to join the current activity. If you pick this one, you get the points, but then you have to jump forward in time to find the next activity that starts after your current one ends. The other path is to skip the activity you are looking at right now so you can check out the next one instead. By comparing these paths, the code keeps track of the best way to gather the most points until you either run out of activities or hit the limit on how many extra things you are allowed to go to. Because it remembers all the decisions it has already looked at, it finds the answer very quickly.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | Rust | TS | |||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 1353: Maximum Number of Events That Can Be Attended
- problem 2008: Maximum Earnings From Taxi
- problem 2054: Two Best Non-Overlapping Events
- problem 2402: Meeting Rooms III
Solved On The Same Day
- problem 1005: Maximize Sum Of Array After K Negations
- problem 935: Knight Dialer
- problem 1029: Two City Scheduling
- problem 1769: Minimum Number of Operations to Move All Balls to Each Box
- problem 2080: Range Frequency Queries
- problem 793: Preimage Size of Factorial Zeroes Function
- problem 878: Nth Magical Number
- problem 902: Numbers At Most N Given Digit Set
- problem 1793: Maximum Score of a Good Subarray
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality