Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.


The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!

Example:


Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

```python

USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
    import resource as _res
except Exception:
    _res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
    from typing import *
except Exception:
    pass
try:
    sys.setrecursionlimit(1_000_000)
except Exception:
    pass
try:
    import site as _site
    try:
        _sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
        for _p in _sys_sites:
            if _p and _p not in sys.path:
                sys.path.append(_p)
    except Exception:
        pass
    try:
        _usp = _site.getusersitepackages()
        if isinstance(_usp, str):
            _usp = [_usp]
        for _p in _usp:
            if _p and _p not in sys.path:
                sys.path.append(_p)
    except Exception:
        pass
except Exception:
    pass

def _disabled_input(*args, **kwargs):
    raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input

ns = {"__name__": "__judge__"}  # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
    if not _k.startswith("_"):
        ns[_k] = _v
_CODE = 'class Solution:\n     def trap(self, height):\n         """\n         :type height: List[int]\n         :rtype: int\n         """\n         # find valleys\n         N = len(height)\n         valleys = [] # a list of [left, right] (not inclusive) bounds of local minimum\n         i = 0\n         while i < N-1:\n             # first go uphills and then down hills until flat or up hills, this is a potential left bound of a valley\n             while i < N-1 and height[i] <= height[i+1]: i += 1\n             while i < N-1 and height[i] > height[i+1]: i += 1 # ensures height[i] <= height[i+1] unless out of bounds\n             j = i\n             while j < N-1 and height[j] == height[j+1]: j += 1 # go through the range of the potential bottom of the valley\n             if j < N-1 and height[j] < height[j+1]: valleys.append([i-1,j+1]) # store a confirmed valley with bottom [i:j+1]\n             i = j\n         \n         # fill water into each valley\n         total_water = 0\n         further_valleys = [] # list of potential valley to merge as those whose left side is higher after water filll\n         k = 0\n         if valleys: # initialize\n             l = valleys[k][0]\n             r = valleys[k][1]\n             old_level = height[l+1]\n         while k < len(valleys):\n             # record bottom level\n             water = 0\n             while l >= 0 and r < N and height[l] >= height[l+1] and height[r-1] <= height[r]: # both sides rising\n                 # fill water at [l+1:r]\n                 new_level = min(height[l], height[r])\n                 water += (new_level - old_level) * (r - l - 1)\n                 old_level = new_level\n                 # advance to the next level in the valley\n                 if l >= 0 and r < N:\n                     # rise only the lower side\n                     if height[l] == height[r]:\n                         l -= 1\n                         r += 1\n                     elif height[l] < height[r]: l -= 1\n                     else: r += 1\n                     # make sure level rises\n                     while l >= 0 and height[l] == height[l+1]: l -= 1\n                     while r < N and height[r-1] == height[r]: r += 1\n             total_water += water\n             \n             # l == -1 or r == N or height[l] < height[l+1] or height[r-1] > height[r]\n             if l >= 0 and r < N:\n                 if height[l] > height[l+1]: # further rise is possible after the next valley is filled\n                     further_valleys.append([l,r])\n                 elif further_valleys and height[further_valleys[-1][1]-1] == height[l+1]: # merge two valleys\n                     old_level = height[l+1] # water already filled to this level\n                     l = further_valleys[-1][0]\n                     further_valleys.pop()\n                     continue # fill the merged valley before moving on\n             \n             # fill the next valley\n             k += 1\n             if k < len(valleys):\n                 l = valleys[k][0]\n                 r = valleys[k][1]\n                 old_level = height[l+1]\n             \n         return total_water'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)

_target = None
_fn_name = 'trap'
if _fn_name:
    if "Solution" in ns:
        try:
            _obj = ns["Solution"]()
            if hasattr(_obj, _fn_name):
                _target = getattr(_obj, _fn_name)
        except Exception:
            _target = None
    if _target is None and _fn_name in ns and callable(ns[_fn_name]):
        _target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
    _cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
    _user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
    if len(_user_funcs) == 1:
        _target = _user_funcs[0]
if _target is None:
    raise RuntimeError(f"Could not resolve callable '{_fn_name}'")

_raw = sys.stdin.read().strip()
if _raw:
    _parsed = json.loads(_raw)
    if isinstance(_parsed, dict):
        _kwargs = _parsed.get("kwargs", {})
        _args = _parsed.get("args", [])
    else:
        _args, _kwargs = _parsed, {}
else:
    _args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
    _args = [_args]
_res = _target(*_args, **_kwargs)
try:
    sys.stdout.write(repr(_res) + "\n")
except Exception:
    pass

```

Measured memory_bytes: 7434