Last active
June 11, 2018 16:27
-
-
Save neerajkumar/4544a2a6a8dfcdf3e73cd1c33c388d36 to your computer and use it in GitHub Desktop.
length of longest consecutive sequence in array of integers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def longest_consecutive_sequence(a) | |
ans = 0 | |
a.length.times do |i| | |
unless a.include?(a[i] - 1) | |
j = a[i] | |
while(a.include?(j)) do | |
j += 1 | |
end | |
ans = j - a[i] if (ans < j - a[i]) | |
end | |
end | |
return ans | |
end | |
puts longest_consecutive_sequence([36, 41, 56, 35, 44, 33, 34, 92, 43, 32, 42]) ## returns 5 i.e. [32, 33, 34, 35, 36] | |
puts longest_consecutive_sequence([1, 9, 3, 10, 4, 20, 2]) ## returns 4 i.e. [1, 2, 3, 4] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment