Job sequencing Problem

Pattern: Activity selection

medium

Each job takes one unit of time and pays its profit if finished by its deadline. Take jobs from most to least profitable, and put each in the latest free time slot at or before its deadline; skip it if none is free. Return the number of jobs done and the total profit.

The problem

Each job is [id, deadline, profit]; a job takes one unit of time, only one job runs at a time, and a job counts only if it finishes by its deadline. Return [number of jobs done, total profit] for the largest total profit. [[1, 4, 20], [2, 1, 10], [3, 1, 40], [4, 1, 30]] gives [2, 60].

Think first

  • Which job should get first claim on a slot?
  • Which slot should it take?
  • Why not the earliest free slot?

Hints

    Brute force, and why it fails

    Try every subset of jobs and check it can be scheduled: O(2ⁿ × n).

    The key insight

    Profitable jobs first, each placed as late as possible, never blocks a job that could have fitted, so the greedy keeps the best total.

    Dry run

    order3 4 1 2

    Jobs (id, deadline, profit): (1, 4, 20), (2, 1, 10), (3, 1, 40), (4, 1, 30). By profit: 3, 4, 1, 2.

    Step 1 of 4

    The plan

    sort jobs by profit, highest first
    used = [false] * (maxDeadline + 1)
    for job: for t from job.deadline down to 1: if not used[t]: use it; count += 1; profit += job.profit; break
    

    Complexity

    Time
    O(n log n + n × D)
    Space
    O(D)

    Sorting, then each job scans at most D slots, where D is the largest deadline. A union-find of free slots makes it near O(n log n).

    Edge cases

    • All deadlines 1: only the most profitable job.
    • Deadlines larger than the number of jobs.
    • One job.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int[] JobScheduling(int[][] jobs) {
            int[][] byProfit = jobs.clone();
            Arrays.sort(byProfit, (a, b) -> b[2] - a[2]);   // most profitable first
            int maxDeadline = 0;
            for (int[] j : jobs) maxDeadline = Math.max(maxDeadline, j[1]);
            boolean[] used = new boolean[maxDeadline + 1];  // used[t]: slot t (from t - 1 to t) is taken
            int count = 0, profit = 0;
            for (int[] j : byProfit) {
                for (int t = Math.min(j[1], maxDeadline); t >= 1; t--) {   // the latest free slot before its deadline
                    if (!used[t]) {
                        used[t] = true;
                        count++;
                        profit += j[2];
                        break;
                    }
                }
            }
            return new int[]{count, profit};
        }
    }

    C++

    class Solution {
    public:
        vector<int> JobScheduling(vector<vector<int>>& jobs) {
            vector<vector<int>> byProfit(jobs);
            sort(byProfit.begin(), byProfit.end(), [](const vector<int>& a, const vector<int>& b) { return a[2] > b[2]; });
            int maxDeadline = 0;
            for (const vector<int>& j : jobs) maxDeadline = max(maxDeadline, j[1]);
            vector<bool> used(maxDeadline + 1, false);  // used[t]: slot t (from t - 1 to t) is taken
            int count = 0, profit = 0;
            for (const vector<int>& j : byProfit) {     // most profitable first
                for (int t = min(j[1], maxDeadline); t >= 1; t--) {   // the latest free slot before its deadline
                    if (!used[t]) {
                        used[t] = true;
                        count++;
                        profit += j[2];
                        break;
                    }
                }
            }
            return vector<int>{count, profit};
        }
    };

    Python

    class Solution:
        def JobScheduling(self, jobs: list[list[int]]) -> list[int]:
            max_deadline = max(d for _, d, _ in jobs)
            used = [False] * (max_deadline + 1)     # used[t]: slot t (from t - 1 to t) is taken
            count = profit = 0
            for _, deadline, p in sorted(jobs, key=lambda j: -j[2]):   # most profitable first
                for t in range(deadline, 0, -1):    # the latest free slot before its deadline
                    if not used[t]:
                        used[t] = True
                        count += 1
                        profit += p
                        break
            return [count, profit]

    Common mistakes

    • Taking the earliest free slot.
    • Sorting by deadline instead of profit.

    Similar problems