Skip to problem
←

Weighted Job Scheduling

Medium 0 attempts

Each entry in jobs is [start, end, profit]. Choose a subset of jobs with no overlapping time intervals and return the largest possible total profit. The jobs may be given in any order.

Touching endpoints are allowed: a job ending at time t is compatible with a job starting at time t. You must take a selected job in full, and each job can be selected at most once. Different entries may have identical times; overlapping jobs cannot both be selected.

Return the profit only, not the chosen jobs. For the first example, the best selection is:

Start End Profit
1 2 50
2 100 200

These jobs meet at time 2, giving 250 total profit. Taking the shorter intermediate jobs would earn less.

Function contract

Implement maxProfit(jobs).

Output: Return the maximum total profit as an integer, not the selected jobs.

Example 1

Input
jobs = [[1,2,50],[3,5,20],[6,19,100],[2,100,200]]
Output
250

Example 2

Input
jobs = [[1,2,5]]
Output
5
Constraints
  • 1 <= jobs.length <= 10^5
  • Each job is [start, end, profit].
  • 1 <= start < end <= 10^9
  • 1 <= profit <= 10^4

Dynamic programming with binary search

Sort by end time. Let dp[i] be the maximum profit obtainable from jobs 0 through i in that sorted order.

For each job, either skip it and keep dp[i - 1], or take its profit plus the best profit before it starts. Binary search finds the last earlier job whose end is less than or equal to the current start. If no earlier job is compatible, taking this job contributes only its own profit.

javascript
function maxProfit(jobs) {
  jobs.sort((a, b) => a[1] - b[1]);
  const n = jobs.length;
  const dp = Array(n).fill(0);
  dp[0] = jobs[0][2];

  function findLast(i) {
    let low = 0, high = i - 1, result = -1;
    while (low <= high) {
      const mid = (low + high) >> 1;
      if (jobs[mid][1] <= jobs[i][0]) {
        result = mid;
        low = mid + 1;
      } else {
        high = mid - 1;
      }
    }
    return result;
  }

  for (let i = 1; i < n; i++) {
    const previous = findLast(i);
    const take = jobs[i][2] + (previous === -1 ? 0 : dp[previous]);
    dp[i] = Math.max(dp[i - 1], take);
  }
  return dp[n - 1];
}

Time: O(n log n), including sorting and binary searches.

Space: O(n) for the DP array and typical sorting workspace. The reference sorts the input array in place. The maximum total profit is 10^9, safely within JavaScript's exact integer range.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript