Skip to content

Commit 23a2912

Browse files
committed
ts-2: longest_chain
1 parent e42450d commit 23a2912

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
function longest_chain_of_consecutive_numbers(nums: number[]): number {
2+
if (nums.length === 0)
3+
return 0;
4+
const num_set = new Set(nums);
5+
let longest_chain = 0;
6+
for (const num of num_set) {
7+
// If the current number is the smallest number in its chain, search for
8+
// the length of its chain.
9+
if (!num_set.has(num - 1)) {
10+
let currentNum = num;
11+
let currentChain = 1;
12+
// Continue to find the next consecutive numbers in the chain.
13+
while (num_set.has(currentNum + 1)) {
14+
currentNum += 1;
15+
currentChain += 1;
16+
}
17+
longest_chain = Math.max(longest_chain, currentChain);
18+
}
19+
}
20+
return longest_chain;
21+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
function longest_chain_of_consecutive_numbers_brute_force(nums: number[]): number {
2+
if (nums.length === 0)
3+
return 0;
4+
let longest_chain = 0;
5+
// Look for chains of consecutive numbers that start from each number.
6+
for (const num of nums) {
7+
let current_num = num;
8+
let current_chain = 1;
9+
// Continue to find the next consecutive numbers in the chain.
10+
while (nums.includes(current_num + 1)) {
11+
current_num += 1;
12+
current_chain += 1;
13+
}
14+
longest_chain = Math.max(longest_chain, current_chain);
15+
}
16+
return longest_chain;
17+
}

0 commit comments

Comments
 (0)