THN Interview Prep

1235. Maximum Profit in Job Scheduling

At a Glance

  • Topic: Array
  • Pattern: Analyze Pattern
  • Difficulty: Hard
  • LeetCode: 1235

Problem Statement

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.

If you choose a job that ends at time X you will be able to start another job that starts at time X.

Example 1:

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. Time range [1-3]+[3-6] , we get profit of 120 = 50 + 70.

Example 2:

Input: startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60] Output: 150 Explanation: The subset chosen is the first, fourth and fifth job. Profit obtained 150 = 20 + 70 + 60.

Example 3:

Input: startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4] Output: 6

Constraints:

1 <= startTime.length == endTime.length == profit.le...

Approach & Solution Steps

Sort jobs by start time. Use DP with memoization. For each job, we can either skip it or schedule it and binary search for the next compatible job.

Optimal JS Solution

function jobScheduling(startTime, endTime, profit) {
  const jobs = startTime.map((start, i) => ({ start, end: endTime[i], profit: profit[i] }));
  jobs.sort((a, b) => a.start - b.start);
  const memo = new Map();

  function dfs(i) {
    if (i === jobs.length) return 0;
    if (memo.has(i)) return memo.get(i);
    
    // Don't include this job
    let res = dfs(i + 1);
    
    // Include this job, binary search for next
    let left = i + 1, right = jobs.length;
    while (left < right) {
      const mid = Math.floor((left + right) / 2);
      if (jobs[mid].start >= jobs[i].end) right = mid;
      else left = mid + 1;
    }
    res = Math.max(res, jobs[i].profit + dfs(left));
    memo.set(i, res);
    return res;
  }
  return dfs(0);
}

Edge Cases & Pitfalls

  • Always consider empty or null inputs.
  • Watch out for off-by-one index errors.

Mark this page when you finish learning it.

Last updated on

Spotted something unclear or wrong on this page?

On this page