1. Recursive Maximum Compatible Subset Search
Intuition
Sort intervals by start coordinate and recursively determine whether to include or exclude each interval. Return n minus the max compatible subset size.
Algorithm
- Step 1: Sort intervals by start time.
- Step 2: Define recursive solve(idx, lastEnd) returning max non-overlapping count.
- Step 3: If idx == n, return 0.
- Step 4: notTake = solve(idx + 1, lastEnd).
- Step 5: If intervals[idx][0] >= lastEnd: take = 1 + solve(idx + 1, intervals[idx][1]).
- Step 6: Return intervals.length - max(take, notTake).
#include <iostream>#include <vector>#include <algorithm> using namespace std; class Solution { int solve(int idx, int lastEnd, const vector<vector<int>>& intervals) { if (idx == intervals.size()) return 0; int notTake = solve(idx + 1, lastEnd, intervals); int take = 0; if (intervals[idx][0] >= lastEnd) { take = 1 + solve(idx + 1, intervals[idx][1], intervals); } return max(take, notTake); }public: int eraseOverlapIntervals(vector<vector<int>>& intervals) { sort(intervals.begin(), intervals.end()); int maxKept = solve(0, -1e9, intervals); return intervals.size() - maxKept; }}; int main() { Solution sol; vector<vector<int>> intervals = {{1, 2}, {2, 3}, {3, 4}, {1, 3}}; cout << "Min Removals: " << sol.eraseOverlapIntervals(intervals) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^N) - Space complexity:
O(N)