Sort by end, take greedily
Time O(n log n) Space O(1) extraSort by second value; take a pair whenever its start is after the last taken end.
pairs = [[1,2],[7,8],[4,5]]state(vars)
Step 1/4Sorted by end: [1,2], [4,5], [7,8]. Nothing is taken yet.
import java.util.Arrays;
class Solution {
public int findLongestChain(int[][] pairs) {
Arrays.sort(pairs, (a, b) -> Integer.compare(a[1], b[1]));
int count = 0;
long end = Long.MIN_VALUE;
for (int[] p : pairs) {
if (p[0] > end) { count++; end = p[1]; }
}
return count;
}
}Verdict: Optimal by the exchange argument; the LIS-style DP is O(n²).