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
1 class Solution { 2 public int count(int l, int r, int[]height) { 3 int min = Math.min(height[l], height[r]); 4 int sum = 0; 5 for (int i = l + 1; i < r; ++i) sum += Math.min(height[i], min); 6 return min * (r - l - 1) - sum; 7 8 } 9 public int trap(int[] height) { 10 int n = height.length; 11 int [][]stack = new int[n][2]; 12 int k = 0; 13 if (n == 0 || n == 1) return 0; 14 15 int i = 0; 16 int ans = 0; 17 while (i < n && height[i] == 0) i++; 18 if (i == n) return 0; 19 stack[k][0] = i++; 20 stack[k++][1] = 0; 21 22 if (i == n) return 0; 23 int temp = 0; 24 while (i < n) { 25 if (height[i] <= height[stack[k - 1][0]]) { 26 stack[k][0] = i; 27 28 stack[k][1] = stack[k - 1][1]; 29 k++; 30 31 32 } else { 33 34 while (k - 1 >= 0 && height[i] >= height[stack[k - 1][0]]) { 35 k--; 36 37 } 38 if (k == 0) { 39 ans += count(stack[0][0], i, height); 40 stack[k][0] = i; 41 stack[k++][1] = 0; 42 temp = 0; 43 } else { 44 45 int temp1 = count(stack[k - 1][0], i, height); 46 47 temp = temp1 + stack[k - 1][1] ; 48 49 stack[k][0] = i; 50 stack[k++][1] = temp; 51 } 52 } 53 i++; 54 } 55 56 return ans + temp; 57 } 58 }