Calculating trapped water

Question

Suppose you're given an array of positive integers representing a 2-D stack of logs where each element is 1 unit wide and each element in the array represents the height of the logs. When it rains, suppose all spots between the logs are filled up.

Given this information, compute how many units of water remain trapped on the map.

Examples:

  • Given [3, 0, 3] we can hold 3 units of water in the middle
  • Given [2, 0, 3, 0, 5] we can hold 5 units (2 in index 1, 3 in index 3)

Solution

Access restricted

Subscribe to premium account to see the solution.

Get premium now