Given an array of intervals, return the minimum number of intervals to remove so the remaining intervals are non-overlapping.
[[1,2],[2,3],[3,4],[1,3]]1end timecurr.start ≥ prevEnd → keep, update prevEndKeeping the interval with the earliest end leaves maximum room for future intervals. When two overlap, we remove the one that ends later (current, since sorted by end).
Trying every subset of intervals is exponential. Greedy works: always keep the interval that ends earliest.
Sort the intervals by end. Keep an interval if it starts at or after the end of the last kept one. Otherwise it overlaps, so remove it, and the earlier end leaves more room for the rest.
Sort by end, and keep the one that finishes first. Removals equal n minus the most intervals you can keep.
Run the animation above on your own input, or watch the 1:13 video explanation of Non-Overlapping Intervals with a dry run and Java code.