Maximum Profit in Job Scheduling — LeetCode 1235 Python Solution

HardArrayBinary SearchDynamic ProgrammingSorting
Problem
#1235
Reading time
3 min

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

Python
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

MeasureComplexity
TimeO(n \times \log n), where n is the number of jobs
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview