Skip to content

Instantly share code, notes, and snippets.

@AhmedNadar
Last active December 27, 2015 02:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AhmedNadar/7254261 to your computer and use it in GitHub Desktop.
Save AhmedNadar/7254261 to your computer and use it in GitHub Desktop.
Calculate the sum of largest 2 element of an array.
#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