Skip to content

Instantly share code, notes, and snippets.

@MBO
Created October 31, 2013 09:50
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 MBO/7247090 to your computer and use it in GitHub Desktop.
Save MBO/7247090 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
def flood(*heights)
stack = []
max = 0
volume = 0
heights.each do |height|
level = [max, height].min
count = 0
while stack.any? and stack.last[0] < level
h, w = stack.pop
volume += w * (level - h)
count += w
end
stack.push( [level, count] ) if count > 0
stack.push( [height, 1] )
max = [max, height].max
end
volume
end
ARGF.each_line do |line|
nums = line.split(/\s+/).map(&:to_i)
puts " => #{flood(*nums)}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment