# Given n non-negative integers representing an # elevation map where the width of each bar is # 1, compute how much water it is able to trap # after raining. def trappableVolume(depthMap) maxLeft = Array.new(depthMap.size, 0) maxRight = Array.new(depthMap.size, 0) maxObserved = depthMap[0] depthMap.each_with_index do |x, i| maxLeft[i] = maxObserved = [x, maxObserved].max end maxObserved = depthMap.last depthMap.to_enum.with_index.reverse_each do |x, i| maxRight[i] = maxObserved = [x, maxObserved].max end depthMap.zip(maxLeft, maxRight).collect do |a| [a[1], a[2]].min - a[0] end.reduce(0, :+) end