Maximum Length of Pair Chain

medium array greedy sorting

Problem

Given an array of n pairs, pair[i] = [a, b], with a < b, a pair (c, d) can follow (a, b) iff b < c. Return the length of the longest chain that can be formed.

Inputpairs = [[1, 2], [2, 3], [3, 4]]
Output2
The chain [1, 2] → [3, 4] has length 2.

def find_longest_chain(pairs):
    pairs.sort(key=lambda p: p[1])
    cur_end = float('-inf')
    count = 0
    for a, b in pairs:
        if a > cur_end:
            count += 1
            cur_end = b
    return count
function findLongestChain(pairs) {
  pairs.sort((p, q) => p[1] - q[1]);
  let curEnd = -Infinity, count = 0;
  for (const [a, b] of pairs) {
    if (a > curEnd) { count++; curEnd = b; }
  }
  return count;
}
class Solution {
    public int findLongestChain(int[][] pairs) {
        Arrays.sort(pairs, (p, q) -> p[1] - q[1]);
        int curEnd = Integer.MIN_VALUE, count = 0;
        for (int[] p : pairs) {
            if (p[0] > curEnd) { count++; curEnd = p[1]; }
        }
        return count;
    }
}
int findLongestChain(vector<vector<int>>& pairs) {
    sort(pairs.begin(), pairs.end(), [](auto& p, auto& q) { return p[1] < q[1]; });
    int curEnd = INT_MIN, count = 0;
    for (auto& p : pairs) {
        if (p[0] > curEnd) { count++; curEnd = p[1]; }
    }
    return count;
}
Time: O(n log n) Space: O(1)