Python 1235.py
class Solution:
def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:
best = 0
todo = [ (+inf, 0) ] # min-heap (end, profit), add a stop marker
# process all jobs, ordered by startTime
for s, e, p in sorted(zip(startTime + [ 10**10 ], endTime + [ 10**10 ], profit + [ 0 ])): # with stop marker, too
# check all finished tasks
while s >= todo[0][0]:
end, profit = heappop(todo)
best = max(best, profit)
# including current job
heappush(todo, (e, best + p))
return best
Difficulty
and has an acceptance rate of about 55% (700k+ 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 jobScheduling method computes the maximum profit obtainable by selecting a subset of non-overlapping jobs. Each job is defined by a start time, an end time, and an associated profit. The algorithm processes the jobs in chronological order of their start times while maintaining a min-heap of candidate jobs sorted by their finishing times. By continuously updating the best profit seen so far, the method returns the optimal total profit without ever revisiting earlier jobs.
Key Steps
The first important operation is the creation of a sentinel entry that guarantees the heap always contains at least one element. This sentinel uses an infinite end time and zero profit, acting as a stop marker for the loop that extracts completed jobs.
best = 0
todo = [ (+inf, 0) ] # min-heap (end, profit) with a stop marker
Next, the algorithm prepares the job list. It appends a dummy job with an extremely large start and end time (10**10) and zero profit. This dummy job ensures that the final iteration will flush any remaining entries from the heap, allowing the final best value to be correctly captured. The jobs are then sorted by start time, which establishes the processing order.
for s, e, p in sorted(
zip(startTime + [10**10],
endTime + [10**10],
profit + [0])
):
Inside the loop, the method removes all jobs from the heap whose end time is less than or equal to the current job’s start time. Each removal updates best with the maximum profit observed so far. This step guarantees that only jobs that have finished before the current start time are considered for profit accumulation.
while s >= todo[0][0]:
end, profit = heappop(todo)
best = max(best, profit)
After clearing finished jobs, the algorithm pushes a new entry onto the heap representing the scenario where the current job is taken. The profit associated with this entry is the sum of the best profit achievable before the current start time (best) and the profit of the current job (p). The end time stored in the heap is the current job’s end time, which will later be used to determine when this profit becomes eligible for inclusion in future calculations.
heappush(todo, (e, best + p))
When the loop finishes, the variable best holds the maximum profit across all possible non-overlapping job selections, and it is returned as the final result.
return best
Edge Cases Handled
The inclusion of a dummy job with a start and end time far beyond any realistic input value ensures that the while-loop that extracts completed jobs will eventually empty the heap. This design automatically handles the situation where the last real job finishes after all other jobs, guaranteeing that its profit is considered in the final best.
The sentinel entry ( +inf, 0 ) placed in the heap at initialization prevents an IndexError when the while-loop checks todo[0][0] before any real jobs have been added. This means the algorithm works correctly even when the input lists are empty, as the dummy job will be the only element processed, and the returned profit will be zero.
Because the jobs are sorted by start time, the algorithm correctly processes jobs that share identical start times. The while-loop condition s >= todo[0][0] ensures that jobs ending exactly at the start of another job are treated as non-overlapping, allowing back-to-back scheduling without loss of profit.
The use of max(best, profit) after each heap pop guarantees that the algorithm retains the highest profit seen so far, even if multiple jobs finish at the same time. This protects against scenarios where several jobs end simultaneously but have different accumulated profits.
Performance Optimizations
The core optimization is the use of a min-heap (todo) to keep track of pending jobs ordered by their end times. By always examining the smallest end time first, the algorithm can discard finished jobs in amortized constant time per removal, avoiding a full scan of all pending jobs at each iteration.
Sorting the combined job list once at the beginning provides a deterministic processing order, eliminating the need for repeated ordering operations during the main loop. This single sort, followed by a linear scan, yields an efficient overall flow.
The sentinel dummy job eliminates the need for explicit checks for an empty heap after each iteration. By guaranteeing that the heap always contains at least one element, the code avoids conditional branches that could otherwise degrade branch prediction performance.
Finally, the calculation best + p is performed only when a job is pushed onto the heap, meaning that the algorithm never recomputes cumulative profits from scratch. This incremental update strategy reduces redundant arithmetic and keeps the inner loop lightweight.
ELI5 - Simplified Explanation
Imagine you have a long list of fun activities you want to do today. Each activity has a starting time, an ending time, and a special prize waiting at the end. Because you can only do one thing at a time, you have to pick the activities that do not overlap so you can collect as many prizes as possible.
The code works like a smart helper organizing your schedule. It looks at all the jobs and puts them in order based on when they start. It keeps a little pile of notes about jobs that are currently happening.
When it is time to start a new job, the helper checks the pile to see if any previous jobs have already finished. If a job is done, the helper looks at the profit collected from it and saves the highest number found so far. Then, it adds the current job to the pile, along with the total profit earned if that job is finished. By the time the helper looks at every single job in the list, it knows exactly which combination of activities gives the biggest reward.
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++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | Python | |||||||
| leetcode.ca | C++ | Java | Python | Go | Swift | TS | ||||
| MemoryLimitExceeded | C++ | Python | ||||||||
| Progiez | C++ | Java | Python | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| chandansgowda | Python | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fsq | C++ | |||||||||
| gouthampradhan | Java | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| martianoff | Scala | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, Swift, TypeScript | |||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| chandansgowda | Python | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fsq | C++ | |||||||||
| gouthampradhan | Java | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| martianoff | Scala | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 930: Binary Subarrays With Sum
- problem 1190: Reverse Substrings Between Each Pair of Parentheses
- problem 1219: Path with Maximum Gold
- problem 446: Arithmetic Slices II - Subsequence
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