[LeetCode] Non-overlapping Intervals

435. Non-overlapping Intervals

Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
int dp[100000];
int helper(vector<vector<int>>& I, int p, int ed) {
if(p == I.size()) return 0;
if(dp[p] != -1) return dp[p];
int& res = dp[p];
res = helper(I,p+1,ed) + 1;
if(ed <= I[p][0]) {
vector<int> tmp{I[p][1],INT_MIN};
int np = lower_bound(I.begin() + p, I.end(), tmp) - I.begin();
res = min(res, helper(I,np, I[p][1]) + np - p - 1);
}
return res;
}
public:
int eraseOverlapIntervals(vector<vector<int>>& I) {
sort(begin(I), end(I));
memset(dp,-1,sizeof(dp));

return helper(I,0,INT_MIN);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/26/PS/LeetCode/non-overlapping-intervals/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.