1. Recursive Pick / Skip with Linear Search
Intuition
Sort jobs and recursively decide whether to include job i or skip it, searching linearly for the next compatible job.
Algorithm
- Sort jobs by startTime.
- In
solve(i): - If
i >= n, return 0. - Option 1 (skip):
solve(i + 1). - Option 2 (take): Find first job
j > iwherestartTime[j] >= endTime[i]by linear scan. - Return
max(Option 1, profit[i] + solve(j)).
#include <iostream>#include <vector>#include <algorithm> using namespace std; struct Job { int start, end, profit;}; class Solution { int solve(int i, const vector<Job>& jobs) { if (i >= jobs.size()) return 0; // Skip int skip = solve(i + 1, jobs); // Take int nextIdx = i + 1; while (nextIdx < jobs.size() && jobs[nextIdx].start < jobs[i].end) { nextIdx++; } int take = jobs[i].profit + solve(nextIdx, jobs); return max(skip, take); }public: int jobScheduling(vector<int>& startTime, vector<int>& endTime, vector<int>& profit) { int n = startTime.size(); vector<Job> jobs(n); for (int i = 0; i < n; ++i) jobs[i] = {startTime[i], endTime[i], profit[i]}; sort(jobs.begin(), jobs.end(), [](const Job& a, const Job& b) { return a.start < b.start; }); return solve(0, jobs); }}; int main() { Solution sol; vector<int> s = {1, 2, 3, 3}; vector<int> e = {3, 4, 5, 6}; vector<int> p = {50, 10, 40, 70}; cout << "Max Profit: " << sol.jobScheduling(s, e, p) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^n) - Space complexity:
O(n) call stack