Created
July 2, 2021 02:58
-
-
Save juanfurattini/2698144d3fc0fb76b22851f30bb1a3dd to your computer and use it in GitHub Desktop.
Second max number
This file contains 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 second_max_number(array) | |
raise 'Argument array must be an enumerable' unless array.is_a?(Enumerable) | |
raise 'Argument array must have at least 2 elements' if array.size < 2 | |
max, second_max = nil | |
array.each do |current| | |
if max.nil? || (!current.nil? && current > max) | |
if second_max.nil? || (!max.nil? && max > second_max) | |
second_max = max | |
end | |
max = current | |
elsif second_max.nil? || (!current.nil? && current > second_max) | |
second_max = current | |
end | |
end | |
second_max | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment