⭐🚀⭐Question : Job sequencing Problem ⭐🚀⭐

Question

You are given a set of N jobs where each job comes with a deadline and profit. The profit can only be earned upon completing the job within its deadline. Find the number of jobs done and the maximum profit that can be obtained. Each job takes a single unit of time and only one job can be performed at a time.

Intuition

Sort jobs by deadline and greedily keep the most profitable set that fits deadlines. Use a min-heap of selected job profits: push a profit when the number of selected jobs is less than the current job's deadline; otherwise, if the current profit is larger than the smallest selected profit, replace it. The heap always contains the best profits for available slots.

Approach

  1. Pair deadlines and profits.
  2. Sort pairs by deadline (ascending).
  3. Use a min-heap to store chosen job profits:
    - If heap.size() < deadline, push profit.
    - Else if profit > heap.top(), pop and push profit.
  4. Sum heap values and count jobs.

Complexity

  • Time complexity: O(n log n) — sorting takes O(n log n) and each heap operation is O(log n).
  • Space complexity: O(n) — for pairs and heap.

Code

C++
Python
Java
JavaScript
class Solution {
  public:
      vector<int> jobSequencing(vector<int> &deadline, vector<int> &profit) {
        
        int n = deadline.size();
        vector<int> ans = {0, 0};
        vector<pair<int, int>> jobs;
        for (int i = 0; i < n; i++) {
            jobs.push_back({deadline[i], profit[i]});
        }
    
        // sort the jobs based on deadline
        // in ascending order
        sort(jobs.begin(), jobs.end());
        priority_queue<int, vector<int>, greater<int>> pq;
    
        for (int i = 0; i < jobs.size(); i++) {
            
            // if job can be scheduled within its deadline
            if (jobs[i].first > pq.size())
                pq.push(jobs[i].second);
            
            // replace the job with the lowest profit
            else if (!pq.empty() && pq.top() < jobs[i].second) {
                pq.pop();
                pq.push(jobs[i].second);
            }
        }
    
        while (!pq.empty()) {
            ans[1] += pq.top();
            pq.pop();
            ans[0]++;
        }
    
        return ans;
    }
};


Comments (0)