You are given an array of n
pairs pairs
where pairs[i] = [left_i, right_i]
and left_i < right_i
.
A pair (c, d)
can follow another pair (a, b)
if and only if b < c
. A chain of pairs can be formed in this fashion.
Return the length of the longest chain which can be formed.
pairs = [[1,2], [2,3], [3,4]]
2
[1,2] -> [3,4]
.pairs = [[1,2], [7,8], [4,5]]
3
[1,2] -> [4,5] -> [7,8]
.left_i < right_i
?
To solve this problem, we can use a greedy algorithm. Here’s the strategy:
cur_end
to negative infinity and chain_length
to 0.cur_end
), update cur_end
to the end of the current pair and increment the chain length.This ensures that we are always trying to extend the chain with the earliest possible end, making our solution both optimal and efficient.
def findLongestChain(pairs):
# Sort pairs by their ending element
pairs.sort(key=lambda x: x[1])
cur_end = float('-inf')
chain_length = 0
for pair in pairs:
if cur_end < pair[0]:
cur_end = pair[1]
chain_length += 1
return chain_length
# Test cases
print(findLongestChain([[1,2], [2,3], [3,4]])) # Output: 2
print(findLongestChain([[1,2], [7,8], [4,5]])) # Output: 3
Therefore, the overall time complexity is O(n log n), which is quite efficient for this problem.
This approach ensures that we can efficiently determine the maximum length of a chain that can be formed using the given pairs.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?