|
U
Pro49. Trapping Rain Water
Med.
Problem Description
Given an array of N non-negative integers representing an elevation map where each bar has width 1, compute how many total units of water can be trapped after raining.
Input Format
- •Line 1: An integer N (1≤N≤105).
- •Line 2: N space-separated non-negative integers A1,…,AN.
Output Format
Print the total units of trapped water.
Example 1:
Input:
12 0 1 0 2 1 0 1 3 2 1 2 1
Output:
6
Explanation: Classic trapping rain water elevation map traps 6 units of water.
Example 2:
Input:
6 4 2 0 3 2 5
Output:
9
Explanation: Water trapped in valleys equals 9.
Example 3:
Input:
3 3 2 1
Output:
0
Explanation: Monotonically decreasing bars trap 0 water.
Constraints:
Standard integer bounds: 32-bit signed integer or input range [1, 10^5].Time complexity target: O(N) or O(N log N) where applicable.Auxiliary space target: O(1) or minimal auxiliary memory.
Follow up:Can this algorithm be adapted to an online streaming setting where the entire input cannot be held in memory simultaneously?
1,180 Online
Code
|Loading Code Editor...
SavedLn 1, Col 1
param_1 =
param_2 =
Sandboxed Engine
Ctrl+Enter = Run | Ctrl+Shift+Enter = Submit