|
| 1 | +class Solution { |
| 2 | + public: |
| 3 | + vector<int> JobSequencing(vector<int> &id, vector<int> &deadline, |
| 4 | + vector<int> &profit) { |
| 5 | + |
| 6 | + // Step 1: Create a vector of tuples to store job details (profit, job id, and deadline) |
| 7 | + vector<tuple<int, int, int>> v; |
| 8 | + |
| 9 | + // Loop through the job arrays and create tuples of (profit, job id, deadline) |
| 10 | + for(int i = 0; i < id.size(); i++){ |
| 11 | + v.push_back(make_tuple(profit[i], id[i], deadline[i])); |
| 12 | + } |
| 13 | + |
| 14 | + // Step 2: Sort the jobs by profit in descending order |
| 15 | + // The job with higher profit is considered first |
| 16 | + sort(v.begin(), v.end(), [](tuple<int, int, int>& a, tuple<int, int, int>& b){ |
| 17 | + return get<0>(a) > get<0>(b); // Compare based on profit (first element of the tuple) |
| 18 | + }); |
| 19 | + |
| 20 | + // Step 3: Find the maximum deadline to define the size of the schedule array |
| 21 | + int maxiDeadline = INT_MIN; |
| 22 | + for(int i = 0; i < deadline.size(); i++){ |
| 23 | + maxiDeadline = max(maxiDeadline, deadline[i]); |
| 24 | + } |
| 25 | + |
| 26 | + // Step 4: Initialize the schedule array with -1 to represent unoccupied time slots |
| 27 | + // The array has size `maxiDeadline + 1` because deadlines are 1-based. |
| 28 | + vector<int> schedule(maxiDeadline+1, -1); |
| 29 | + |
| 30 | + // Step 5: Initialize variables to track the number of jobs selected and total profit |
| 31 | + int count = 0; |
| 32 | + int maxProfit = 0; |
| 33 | + |
| 34 | + // Step 6: Try to schedule jobs in decreasing order of their profit |
| 35 | + for(int i = 0; i < v.size(); i++){ |
| 36 | + int currProfit = get<0>(v[i]); // Profit of the current job |
| 37 | + int currJobId = get<1>(v[i]); // Job id of the current job |
| 38 | + int currDeadline = get<2>(v[i]); // Deadline of the current job |
| 39 | + |
| 40 | + // Step 7: Try to find the latest available time slot before the job's deadline |
| 41 | + for(int k = currDeadline; k > 0; k--){ |
| 42 | + // If the time slot is free (schedule[k] == -1), schedule the job there |
| 43 | + if(schedule[k] == -1){ |
| 44 | + schedule[k] = currJobId; // Assign the job id to the available slot |
| 45 | + maxProfit += currProfit; // Add the profit of the job to the total profit |
| 46 | + count++; // Increment the count of scheduled jobs |
| 47 | + break; // Break out of the loop after scheduling the job |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + // Step 8: Return the count of jobs scheduled and the total profit |
| 53 | + return {count, maxProfit}; |
| 54 | + } |
| 55 | +}; |
0 commit comments