Skip to main content

Trap Rain Water

HardPremium

Given an array of non-negative integers representing the heights of bars in a histogram, compute the amount of water that can be trapped between the bars after a rainfall.

The histogram is represented by an array where the width of each bar is 1. Water can be trapped if there are dips between taller bars that can hold the water.

Example

Input: [5, 0, 4] Output: 4 Explanation: Amount of water trapped is limited by shorter bar Input: [1, 1, 1] Output: 0 Explanation: No water can be trapped