1. Backtracking Schedule Search
Intuition
Recursively try including and placing each job into available slots to evaluate all feasible subsets and maximize total profit.
Algorithm
- Step 1: Define a recursive backtracking function testing whether each job is included.
- Step 2: For each chosen subset, verify if a feasible deadline-compatible assignment of time slots exists.
- Step 3: Track and update the maximum profit achieved and corresponding job count.
- Step 4: Return the optimal count and profit.
#include <iostream>#include <vector>#include <algorithm> using namespace std; struct Job { int id, dead, profit;}; class Solution { int maxProfit = 0; int maxJobs = 0; void backtrack(int idx, const vector<Job>& jobs, vector<bool>& slotUsed, int currentProfit, int currentJobs) { if (idx == jobs.size()) { if (currentProfit > maxProfit) { maxProfit = currentProfit; maxJobs = currentJobs; } else if (currentProfit == maxProfit) { maxJobs = max(maxJobs, currentJobs); } return; } // Option 1: Do not pick current job backtrack(idx + 1, jobs, slotUsed, currentProfit, currentJobs); // Option 2: Try picking current job in any valid slot for (int t = min((int)slotUsed.size() - 1, jobs[idx].dead); t >= 1; --t) { if (!slotUsed[t]) { slotUsed[t] = true; backtrack(idx + 1, jobs, slotUsed, currentProfit + jobs[idx].profit, currentJobs + 1); slotUsed[t] = false; break; // Greedily latest slot is always preferred } } } public: vector<int> JobScheduling(Job arr[], int n) { vector<Job> jobs(arr, arr + n); int maxDead = 0; for (int i = 0; i < n; ++i) maxDead = max(maxDead, arr[i].dead); vector<bool> slotUsed(maxDead + 1, false); maxProfit = 0; maxJobs = 0; backtrack(0, jobs, slotUsed, 0, 0); return {maxJobs, maxProfit}; }}; int main() { Solution sol; Job arr[] = {{1, 4, 20}, {2, 1, 10}, {3, 1, 40}, {4, 1, 30}}; int n = sizeof(arr) / sizeof(arr[0]); vector<int> ans = sol.JobScheduling(arr, n); cout << "Jobs Done: " << ans[0] << ", Max Profit: " << ans[1] << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^N) - Space complexity:
O(N)