Job Scheduling Algo

Pattern: Activity selection

medium

When jobs have different profits, counting jobs is not enough, so use dynamic programming. Sort by end time; for each job, either skip it or take it plus the best answer among jobs that end by its start, found with binary search. O(n log n).

The problem

Each job has a start, an end and a profit. Choose jobs that do not overlap (a job may start exactly when another ends) to get the largest total profit. start = [1, 2, 3, 3], end = [3, 4, 5, 6], profit = [50, 10, 40, 70] gives 120.

The linked GFG page is Weighted Job Scheduling, which this is; this guide uses LeetCode's argument order.

Think first

  • Does the earliest-finish greedy still work?
  • For one job, what are the two choices?
  • How do you find the last job compatible with it quickly?

Hints

    Brute force, and why it fails

    Try every subset: O(2ⁿ × n).

    The key insight

    After sorting by end, the best answer for the first i jobs depends only on smaller prefixes, so best[i] = max(best[i - 1], best[k] + profit) where k counts the compatible jobs.

    Dry run

    best0

    start [1, 2, 3, 3], end [3, 4, 5, 6], profit [50, 10, 40, 70]. Sorted by end already.

    Step 1 of 4

    The plan

    sort jobs by end
    best[0] = 0
    for i in 1..n:
        k = number of jobs among the first i - 1 whose end <= job i's start
        best[i] = max(best[i - 1], best[k] + profit_i)
    

    Complexity

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

    Sorting plus one binary search per job.

    Edge cases

    • A job that starts exactly when another ends can follow it.
    • One job.
    • All jobs overlap: the most profitable one.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int jobScheduling(int[] startTime, int[] endTime, int[] profit) {
            int n = startTime.length;
            int[][] jobs = new int[n][];
            for (int i = 0; i < n; i++) jobs[i] = new int[]{startTime[i], endTime[i], profit[i]};
            Arrays.sort(jobs, (a, b) -> Integer.compare(a[1], b[1]));   // by end time
            int[] best = new int[n + 1];            // best[i]: the most profit using the first i jobs
            for (int i = 1; i <= n; i++) {
                int[] job = jobs[i - 1];
                int lo = 0, hi = i - 1;             // how many earlier jobs end by this job's start?
                while (lo < hi) {
                    int mid = (lo + hi + 1) / 2;
                    if (jobs[mid - 1][1] <= job[0]) lo = mid; else hi = mid - 1;
                }
                best[i] = Math.max(best[i - 1], best[lo] + job[2]);   // skip it, or take it after the compatible ones
            }
            return best[n];
        }
    }

    C++

    class Solution {
    public:
        int jobScheduling(vector<int>& startTime, vector<int>& endTime, vector<int>& profit) {
            int n = static_cast<int>(startTime.size());
            vector<vector<int>> jobs;
            for (int i = 0; i < n; i++) jobs.push_back(vector<int>{startTime[i], endTime[i], profit[i]});
            sort(jobs.begin(), jobs.end(), [](const vector<int>& a, const vector<int>& b) { return a[1] < b[1]; });   // by end
            vector<int> best(n + 1, 0);             // best[i]: the most profit using the first i jobs
            for (int i = 1; i <= n; i++) {
                const vector<int>& job = jobs[i - 1];
                int lo = 0, hi = i - 1;             // how many earlier jobs end by this job's start?
                while (lo < hi) {
                    int mid = (lo + hi + 1) / 2;
                    if (jobs[mid - 1][1] <= job[0]) lo = mid; else hi = mid - 1;
                }
                best[i] = max(best[i - 1], best[lo] + job[2]);   // skip it, or take it after the compatible ones
            }
            return best[n];
        }
    };

    Python

    import bisect
    
    class Solution:
        def jobScheduling(self, startTime: list[int], endTime: list[int], profit: list[int]) -> int:
            jobs = sorted(zip(startTime, endTime, profit), key=lambda j: j[1])   # by end time
            ends = [e for _, e, _ in jobs]
            best = [0] * (len(jobs) + 1)            # best[i]: the most profit using the first i jobs
            for i, (s, e, p) in enumerate(jobs, 1):
                k = bisect.bisect_right(ends, s, 0, i - 1)   # earlier jobs that end by this start
                best[i] = max(best[i - 1], best[k] + p)      # skip it, or take it after the compatible ones
            return best[-1]

    Common mistakes

    • Using the meeting-room greedy, which maximises the count, not the profit.
    • Binary searching over unsorted ends.

    Similar problems