Last active
January 16, 2018 20:59
-
-
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.
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
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