Skip to content

Instantly share code, notes, and snippets.

@finsterthecat
Last active January 16, 2018 20:59
Show Gist options
  • Save finsterthecat/7450338 to your computer and use it in GitHub Desktop.
Save finsterthecat/7450338 to your computer and use it in GitHub Desktop.
Ruby solution for http://qandwhat.apps.runkite.com/i-failed-a-twitter-interview/. A bit more verbose but perhaps slightly more efficient solution than others? Nope, just more verbose.
walls = [2,5,1,2,3,4,7,7,6]
# array of max values of elements to the left for each element
def running_max(_walls)
maxmin = 0
_walls.inject([]) do |maxes, c|
maxes << if (c < maxmin) then
maxmin
else
maxmin = c
end
maxes
end
end
running_max_left = running_max(walls)
running_max_right = running_max(walls.reverse).reverse
water_volume = 0
walls.each_with_index do |f, i|
min_wall = [running_max_left[i], running_max_right[i]].min
water_volume += [min_wall - f, 0].max
end
puts "Total water volume is #{water_volume}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment