Maximum Profit in Job Scheduling — LeetCode 1235 Python Solution
- Problem
- #1235
- Pattern
- Monotonic Stack
- Reading time
- 3 min
- Source
- leetcode.com
The problem
We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i]. You're given the startTime, endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.
Example
- Input
- startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]
- Output
- 120
- Explanation
- The subset chosen is the first and fourth job.
Python solution
class Solution:
def jobScheduling(
self, startTime: List[int], endTime: List[int], profit: List[int]
) -> int:
@cache
def dfs(i):
if i >= n:
return 0
_, e, p = jobs[i]
j = bisect_left(jobs, e, lo=i + 1, key=lambda x: x[0])
return max(dfs(i + 1), p + dfs(j))
jobs = sorted(zip(startTime, endTime, profit))
n = len(profit)
return dfs(0)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n), where n is the number of jobs |
| Space | O(1) auxiliary |
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 1235. Maximum Profit in Job Scheduling is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
On a study list
This problem is on Grind 75.
Frequently asked questions
- How hard is LeetCode 1235. Maximum Profit in Job Scheduling?
- LeetCode 1235. Maximum Profit in Job Scheduling is rated Hard on LeetCode.
- What is the time complexity of LeetCode 1235. Maximum Profit in Job Scheduling?
- The Python solution on this page runs in O(n \times \log n), where n is the number of jobs.
- What is the space complexity of LeetCode 1235. Maximum Profit in Job Scheduling?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1235. Maximum Profit in Job Scheduling cover?
- LeetCode 1235. Maximum Profit in Job Scheduling is tagged Array, Binary Search, Dynamic Programming and Sorting on LeetCode.