Skip to content

Instantly share code, notes, and snippets.

@Turskyi
Created May 5, 2022 16:56
Show Gist options
  • Save Turskyi/5b88332772753379088f305b816a88f1 to your computer and use it in GitHub Desktop.
Save Turskyi/5b88332772753379088f305b816a88f1 to your computer and use it in GitHub Desktop.
You are given n pairs of numbers and asked to form a chain. Two pairs of numbers can create a link in the chain if the second number in the first pair is less than the first number in the second pair. Return the length of the longest chain you can form.
fun findLongestChain(pairs: Array<IntArray>): Int {
return if (pairs.isEmpty()) {
0
} else {
var count: Int = 1
pairs.sortWith(compareBy { it[1] })
var end: Int = pairs[0][1]
for (i: Int in 1..pairs.lastIndex) {
if (end < pairs[i][0]) {
count++
end = pairs[i][1]
}
}
count
}
}
/*
You are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti < righti.
A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c. A chain of pairs can be formed in this fashion.
Return the length longest chain which can be formed.
You do not need to use up all the given intervals. You can select pairs in any order.
Example 1:
Input: pairs = [[1,2],[2,3],[3,4]]
Output: 2
Explanation: The longest chain is [1,2] -> [3,4].
Example 2:
Input: pairs = [[1,2],[7,8],[4,5]]
Output: 3
Explanation: The longest chain is [1,2] -> [4,5] -> [7,8].
* */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment