Skip to content
BytePatterns

Water Held Between Bars

HardArrays#two-pointers#running-maximum~35m

Problem

A row of bars of width 1 stands on flat ground, with heights given as non-negative whole numbers. After heavy rain, water settles in the dips between bars and anything above the lower of the surrounding walls runs off. Return the total units of water the row holds. Answer with one pass and constant extra memory.

Examples

Input:  heights = [3, 0, 2, 0, 4, 1, 2]
Output: 8
Why:    3 + 1 + 3 units between the 3 and the 4, and 1 unit over the 1
Input:  heights = [1, 2, 3, 4]
Output: 0
Why:    a staircase has no dip for water to sit in
Input:  heights = []
Output: 0
Why:    edge case, no bars hold no water

Hints

0 / 3

Stuck on the idea rather than the code? Container With Most Water covers it.