[LeetCode] Trapping Rain Water
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 class Solution { 2 public: 3 int trap(int A[], int n) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 vector<int> left(n); 7 int maxHeight = 0; 8 for(int i = 0; i < n; i++) 9 { 10 left[i] = maxHeight; 11 maxHeight = max(maxHeight, A[i]); 12 } 13 14 vector<int> right(n); 15 maxHeight = 0; 16 for(int i = n - 1; i >= 0; i--) 17 { 18 right[i] = maxHeight; 19 maxHeight = max(maxHeight, A[i]); 20 } 21 22 int water = 0; 23 for(int i = 0; i < n; i++) 24 { 25 int height = min(left[i], right[i]) - A[i]; 26 if (height < 0) 27 height = 0; 28 water += height; 29 } 30 31 return water; 32 } 33 };
1 struct Node 2 { 3 int val; 4 int index; 5 Node(){} 6 Node(int v, int idx):val(v), index(idx){} 7 }; 8 9 class Solution { 10 public: 11 int trap(int A[], int n) { 12 // Start typing your C/C++ solution below 13 // DO NOT write int main() function 14 stack<Node> s; 15 int sum = 0; 16 for(int i = 0; i < n; i++) 17 if (s.empty()) 18 s.push(Node(A[i], i)); 19 else 20 { 21 int height = 0; 22 while(!s.empty()) 23 { 24 Node node = s.top(); 25 if (node.val > A[i]) 26 { 27 int width = i - node.index - 1; 28 sum += A[i] * width - height * width; 29 s.push(Node(A[i], i)); 30 break; 31 } 32 else 33 { 34 int width = i - node.index - 1; 35 sum += node.val * width - height * width; 36 height = node.val; 37 s.pop(); 38 } 39 } 40 41 if (s.empty()) 42 s.push(Node(A[i], i)); 43 } 44 45 return sum; 46 } 47 };