Skip to content

Commit 909f627

Browse files
committed
Add Longest Chain Of Consecutive Numbers
1 parent b4f0e1a commit 909f627

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
fun longestChainOfConsecutiveNumbers(nums: List<Int>): Int {
2+
if (nums.isEmpty()) {
3+
return 0
4+
}
5+
val numSet = nums.toSet()
6+
var longestChain = 0
7+
for (num in numSet) {
8+
// If the current number is the smallest number in its chain, search for
9+
// the length of its chain.
10+
if (num - 1 !in numSet) {
11+
var currentNum = num
12+
var currentChain = 1
13+
// Continue to find the next consecutive numbers in the chain.
14+
while (currentNum + 1 in numSet) {
15+
currentNum++
16+
currentChain++
17+
}
18+
longestChain = maxOf(longestChain, currentChain)
19+
}
20+
}
21+
return longestChain
22+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
fun longestChainOfConsecutiveNumbersBruteForce(nums: List<Int>): Int {
2+
if (nums.isEmpty()) {
3+
return 0
4+
}
5+
var longestChain = 0
6+
// Look for chains of consecutive numbers that start from each number.
7+
for (num in nums) {
8+
var currentNum = num
9+
var currentChain = 1
10+
// Continue to find the next consecutive numbers in the chain.
11+
while (currentNum + 1 in nums) {
12+
currentNum++
13+
currentChain++
14+
}
15+
longestChain = maxOf(longestChain, currentChain)
16+
}
17+
return longestChain
18+
}

0 commit comments

Comments
 (0)