Skip to content

Instantly share code, notes, and snippets.

@jiachen247
Last active March 5, 2021 14:02
Show Gist options
  • Save jiachen247/52106660c53366f6e95af26317d62d89 to your computer and use it in GitHub Desktop.
Save jiachen247/52106660c53366f6e95af26317d62d89 to your computer and use it in GitHub Desktop.
def count_water(walls):
n = len(walls)
stack = list() # use a list as a stack
stack.append((walls[0], 0)) # base case
# go over the list of walls once
for i in range(1, n):
current_wall_height = walls[i]
prev_wall_height = stack[-1][0]
if current_wall_height < prev_wall_height:
# draw new box
stack.append((current_wall_height, 1)) # push
else:
# this wall is higher equal to the prev
# see if we can merge with prev boxes
new_width = 1
prev_height = 0
while len(stack) > 0:
prev_height = stack[-1][0]
if prev_height > current_wall_height:
break
else:
(_, width) = stack.pop()
new_width += width
# merged box
stack.append((min(prev_height, current_wall_height), new_width))
# [(11, 1), (8, 3), (6, 1)]
print(stack)
water = 0
for (height, width) in stack:
water += height * width * 1000
return water
walls = [11, 13, 7, 6, 8, 6]
water_count = count_water(walls)
print(water_count)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment