Skip to content
BytePatterns

Longest Chain of Pairs

MediumGreedy#greedy#sort-by-end#interval-scheduling~20m

Problem

You are given a list of pairs [a, b] with a < b. A pair [c, d] can follow a pair [a, b] in a chain when b < c. Pairs may be used in any order, each at most once. Return the length of the longest chain you can build.

Examples

Input:  pairs = [[1, 2], [2, 3], [3, 4]]
Output: 2
Why:    [1, 2] then [3, 4]; [2, 3] cannot follow [1, 2] because 2 is not less than 2
Input:  pairs = [[5, 24], [15, 25], [27, 40], [50, 60]]
Output: 3
Why:    [5, 24], [27, 40], [50, 60]
Input:  pairs = [[1, 2], [7, 8], [4, 5]]
Output: 3
Why:    edge case, the input order does not matter, so all three chain

Hints

0 / 3

Stuck on the idea rather than the code? Interval Scheduling covers it.