#1235

Maximum Profit in Job Scheduling

Hard
ArrayBinary SearchDynamic ProgrammingSortingDynamic ProgrammingBinary SearchSorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal approach uses dynamic programming combined with binary search. By sorting jobs by their end times and using a DP array to store maximum profits, we can efficiently find the best non-overlapping job combinations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a list of jobs and sort it by end time.
  2. 2Step 2: Initialize a DP array where dp[i] represents the maximum profit up to job i.
  3. 3Step 3: For each job, use binary search to find the last non-overlapping job and update dp[i] accordingly.
  4. 4Step 4: Return the maximum value in the DP array.
solution.py16 lines
1# Full working Python code
2from bisect import bisect_right
3
4def maxProfit(startTime, endTime, profit):
5    jobs = sorted(zip(startTime, endTime, profit), key=lambda x: x[1])
6    n = len(jobs)
7    dp = [0] * n
8    for i in range(n):
9        dp[i] = jobs[i][2]  # profit of current job
10        # Find the last non-overlapping job
11        j = bisect_right([jobs[k][1] for k in range(n)], jobs[i][0]) - 1
12        if j != -1:
13            dp[i] += dp[j]
14        if i > 0:
15            dp[i] = max(dp[i], dp[i - 1])  # max profit up to i
16    return dp[-1]

Complexity note: The complexity is O(n log n) due to the sorting step, and O(n) for the DP array, making it efficient for larger inputs.

  • 1Sorting jobs by end time allows us to efficiently find non-overlapping jobs.
  • 2Dynamic programming helps in building solutions incrementally by storing results of subproblems.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.