Last active
December 27, 2015 02:39
-
-
Save AhmedNadar/7254261 to your computer and use it in GitHub Desktop.
Calculate the sum of largest 2 element of an array.
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
#Calculate the sum of largest 2 elements of an array. | |
def max_2_sum(arr) | |
arr.inject([0, 0]) do |largest, el| | |
if largest[0] < el | |
largest[1] = largest[0] | |
largest[0] = el | |
elsif largest[1] < el | |
largest[1] = el | |
end | |
largest | |
end.inject(:+) | |
end | |
#or use shortcut | |
def max_2_sum(arr) | |
sorted = arr.sort | |
sorted[-1] + sorted[-2] | |
end | |
p max_2_sum([3, 4, 5, -2, -3, 5, 9]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment