Maximum Profit in Job Scheduling solution explained

Maximum Profit in Job Scheduling is weighted interval scheduling: sort the jobs by end time, then for each job choose the better of skipping it or taking it plus the best total from jobs that finish by its start. A binary search finds that earlier cutoff, so the whole solution runs in O(n log n) time with O(n) extra memory.

By Published 8 min read

The problem in plain words

Picture a freelancer looking at a list of gigs. Each gig has a start time, an end time and a fee. The freelancer can only work one gig at a time, but a gig that begins at the very moment another ends is fine. Which set of gigs earns the most? The input usually arrives as three parallel lists of equal length: starts, ends and fees. The output is a single number, the largest total fee.

Small examples, written for this page
Jobs as (start, end, fee)Best totalChosen jobs
(1, 3, 20), (2, 5, 20), (4, 7, 70), (6, 8, 30)90(1, 3) then (4, 7)
(1, 3, 5), (3, 6, 5)10Touching end and start is allowed
(1, 10, 50), (1, 2, 10), (2, 3, 10), (3, 4, 10)50One long job beats a chain of short ones
(2, 4, 8)8A single job is always taken
Small examples, written for this page. Scroll sideways on a small screen.

Questions worth asking first: are the lists already sorted (normally not), can two jobs have the same end time (yes), is the end strictly after the start (usually yes), and can fees be zero? Also confirm the touching rule, because some versions of interval problems treat a shared endpoint as a clash.

Why greedy is not enough

Without fees, picking the job that ends earliest and repeating is optimal. That is the classic activity selection result. Fees break it. In the third example, earliest-finish picks the three short jobs for a total of 30 and never takes the long job worth 50. Choosing by highest fee fails too: a big fee on a job that blocks two medium ones can lose. Once a greedy rule fails on a small case, reach for DP. Saying this out loud is part of what the interviewer wants to hear.

Setting up the recurrence

Sort the jobs by end time. Let best[i] be the most you can earn using only the first i jobs in that order, with best[0] = 0. For the job at position i (0-based) there are two choices. Skip it, and you keep best[i]. Take it, and you earn its fee plus best[j], where j counts how many of the earlier jobs end at or before this job's start. Those j jobs are exactly the ones that can sit before it without overlap, and because the list is sorted by end, they form a prefix. So best[i + 1] = max(best[i], fee + best[j]).

The prefix property is the key insight. If job x ends by the start of job i, every job that ends earlier than x also does. That is why one number j is enough, and why a binary search can find it.

Slow approach: scan back for the compatible prefix

The direct implementation walks backward from position i until it hits a job that ends at or before the current start. In the worst case that walk covers every earlier job, so the total is O(n²). Trying every subset would be O(2ⁿ), so even this version is a real improvement and worth stating.

def job_profit_slow(start, end, fee):
    jobs = sorted(zip(end, start, fee))
    n = len(jobs)
    best = [0] * (n + 1)
    for i in range(n):
        e, s, f = jobs[i]
        j = i
        while j > 0 and jobs[j - 1][0] > s:
            j -= 1
        best[i + 1] = max(best[i], best[j] + f)
    return best[n]
Python, O(n²): the recurrence with a linear search.

Main approach: sort by end, binary search the cutoff

Keep a separate list of the sorted end times. For job i, the count j is the number of end times among the first i that are at most its start. In Python, bisect_right on that list gives it directly; passing i as the upper bound keeps the search inside the earlier jobs. Each job then costs O(log n), and the sort dominates at O(n log n).

from bisect import bisect_right

def job_profit(start, end, fee):
    jobs = sorted(zip(end, start, fee))
    ends = [e for e, _, _ in jobs]
    best = [0] * (len(jobs) + 1)
    for i, (e, s, f) in enumerate(jobs):
        j = bisect_right(ends, s, 0, i)  # earlier jobs ending at or before s
        best[i + 1] = max(best[i], best[j] + f)
    return best[-1]
Python: O(n log n) time, O(n) extra space.

JavaScript has no bisect, so write the search by hand. The loop below finds the first earlier position whose end is greater than the start, which equals the count of compatible jobs.

function jobProfit(start, end, fee) {
  const jobs = start.map((s, i) => [end[i], s, fee[i]]);
  jobs.sort((a, b) => a[0] - b[0]);
  const best = new Array(jobs.length + 1).fill(0);
  for (let i = 0; i < jobs.length; i++) {
    const [, s, f] = jobs[i];
    let lo = 0, hi = i;
    while (lo < hi) {
      const mid = (lo + hi) >> 1;
      if (jobs[mid][0] <= s) lo = mid + 1;
      else hi = mid;
    }
    best[i + 1] = Math.max(best[i], best[lo] + f);
  }
  return best[jobs.length];
}
JavaScript: the same plan with a hand-written upper-bound search.

Walking through the first example

Sorted by end, the jobs are (1, 3, 20), (2, 5, 20), (4, 7, 70), (6, 8, 30), with end list [3, 5, 7, 8]. Job one: nothing earlier, so best[1] = 20. Job two starts at 2 and no earlier job ends by 2, so best[2] = max(20, 0 + 20) = 20. Job three starts at 4; one earlier end (3) is at most 4, so best[3] = max(20, best[1] + 70) = 90. Job four starts at 6; ends 3 and 5 qualify, so the take option is best[2] + 30 = 50, and best[4] stays 90.

Complexity

Cost of each method
MethodTimeExtra spaceComment
All subsetsO(2ⁿ · n)O(n)Only for checking answers on tiny inputs
Sorted DP, linear scan backO(n²)O(n)Correct, but slow on tens of thousands of jobs
Sorted DP, binary searchO(n log n)O(n)The expected answer
Cost of each method. Scroll sideways on a small screen.

A common alternative sorts by start time and memoizes a recursive function that, from job i, either skips to i + 1 or jumps to the first job whose start is at least this job's end. It has the same complexity. Pick whichever you can explain more cleanly; interviewers accept both. A third option uses a min-heap keyed by end time while sweeping starts, also O(n log n).

Edge cases to test

  • One job: the answer is its fee.
  • Jobs that share an endpoint, such as (1, 3) and (3, 6): both may be taken.
  • Several jobs with the same end time: the sort order between them must not matter, and with bisect_right bounded by i it does not.
  • Jobs that all overlap each other: the answer is the single largest fee.
  • Jobs listed in random order: never assume the input is pre-sorted.
  • Large fees in a fixed-width integer language: the sum of many fees can exceed 32 bits, so use a 64-bit type.

Mistakes that cost points

  • Sorting by start time but then searching as if the list were sorted by end, which finds the wrong prefix.
  • Using bisect_left, or a strict less-than, so a job that ends exactly at the start is wrongly treated as a clash.
  • Storing best by job index without the extra leading zero, then reading best[-1] or best[j - 1] off by one.
  • Forgetting to carry best[i] forward when the job is skipped, which makes best non-monotonic and breaks the lookup.
  • Sorting the three input lists separately, which scrambles which fee belongs to which interval.
  • Answering with a greedy rule and defending it after a counterexample appears. Move to DP as soon as one fails.

How to explain it out loud

Fictional example

Pitching the recurrence in under a minute
Candidate
Earliest-finish greedy works without fees, but fees break it, so I will use DP. I sort jobs by end time so that the jobs compatible with any job form a prefix.
Candidate
best[i + 1] is the larger of skipping job i, which is best[i], or taking it, which is its fee plus best[j], where j is how many earlier jobs end by its start. I find j with a binary search on the end times.
Candidate
Sorting is O(n log n) and each search is O(log n), so the total is O(n log n) with an O(n) table. I will test with two touching jobs to check the boundary.

Other problems in this set

If you liked the 'skip or take' structure, the same thinking runs through Best Time to Buy and Sell Stock IV, where the states are trades instead of intervals. For interval problems that a greedy rule does solve, Video Stitching is a good contrast: there the goal is coverage, not payment, and extending the farthest reach is provably optimal. The data structure interview questions page covers the sorting and search tools behind both.

Practice it with Natively

Natively helps you rehearse problems like this on your own machine. Snap a screenshot of the prompt and it can read it and propose a direction, such as weighted interval DP, which you can weigh against your own plan once you have tried. It also writes a live transcript of a mock interview, so you can review whether you explained why greedy fails before jumping to the table. Learn about an AI interview assistant for Mac and Windows.

Questions people ask

What is the best approach for Maximum Profit in Job Scheduling?

Sort jobs by end time and build best[i], the top profit using the first i jobs. For each job, take the larger of skipping it or adding its profit to best[j], where j is found by binary search as the number of earlier jobs ending by its start. That is O(n log n) time.

Why does a greedy approach fail here?

Picking the earliest-ending job ignores profit, and picking the highest profit ignores how many other jobs it blocks. A small example with one long, well-paid job against a chain of short ones breaks both rules, so dynamic programming is needed.

Can a job start at the same time another one ends?

In the usual statement, yes. That is why the binary search uses an upper bound (bisect_right) so a job ending exactly at the start time counts as compatible.

Is there a version that sorts by start time instead?

Yes. Sort by start and memoize a function that either skips to the next job or jumps to the first job starting at or after the current end. It has the same O(n log n) cost.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP