Sort + LIS
Time O(n log n) Space O(n)Sort (w ascending, h descending); run the tails LIS on heights.
import java.util.Arrays;
class Solution {
public int maxEnvelopes(int[][] envelopes) {
Arrays.sort(envelopes, (a, b) -> a[0] != b[0] ? Integer.compare(a[0], b[0]) : Integer.compare(b[1], a[1]));
int[] tails = new int[envelopes.length];
int size = 0;
for (int[] e : envelopes) {
int lo = 0, hi = size, h = e[1];
while (lo < hi) {
int mid = (lo + hi) >>> 1;
if (tails[mid] < h) lo = mid + 1; else hi = mid;
}
tails[lo] = h;
if (lo == size) size++;
}
return size;
}
}Verdict: The descending tie-break is the trick.