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.
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.
Input: bars = [1,2,3,4] Output: 0
The bars only rise, so water runs off the left edge.
0 <= bars.length <= 1000000 <= bars[i] <= 10^5Run 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).
I'm here to help with #104 Water Held by a Bar Chart. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.