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.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1]
, return 6
.
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!
1 public class Solution { 2 public int Trap(int[] height) { 3 if (height.Length <= 1) return 0; 4 5 var leftHighest = new int[height.Length]; 6 7 var curMax = 0; 8 for (int i = 0; i < height.Length; i++) 9 { 10 curMax = Math.Max(curMax, height[i]); 11 leftHighest[i] = curMax; 12 } 13 14 var result = 0; 15 curMax = 0; 16 17 for (int i = height.Length - 1; i >= 0; i--) 18 { 19 curMax = Math.Max(curMax, height[i]); 20 if (curMax > height[i] && leftHighest[i] > height[i]) 21 { 22 result = result + Math.Min(curMax, leftHighest[i]) - height[i]; 23 } 24 } 25 26 return result; 27 } 28 }