Skip to the code
cf.
+50 XP

#104 Water Held by a Bar Chart

hard

A playful loading screen fills a bar chart with water. Each bar is one unit wide and bars[i] units tall. Water poured over the chart settles in the dips between taller bars; it runs off at the left and right edges.

Write waterHeld(bars) that returns how many units of water the chart holds. Above bar i, the water rises to the smaller of the tallest bar on its left and the tallest bar on its right (including itself), minus bars[i].

Aim for O(n) time and O(1) extra memory.

Example 1

Input: bars = [3,0,2,0,4]
Output: 7

The water level is 3 over the middle three bars, holding 3 + 1 + 3 = 7 units.

Example 2

Input: bars = [1,2,3,4]
Output: 0

The bars only rise, so water runs off the left edge.

Constraints

  • 0 <= bars.length <= 100000
  • 0 <= bars[i] <= 10^5
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).