Given n non-negative integers representing an elevation map where the width of each bar are 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 the Rain Water (blue section) is being trapped. Thanks Marcos for contributing this image!
Method I
This problem uses a stack that is similar to the largest Rectangle in histogram algorithm. If the stack is smaller than the top or the stack is empty, push into the stack, and if it is larger than the top of the stack, calculate the area around it. In order not to repeat the area, calculate only at the top of the stack, at the top of the stack (the top of the stack after the pop) and the current number of rectangular area (line 13).
1 classSolution {2 Public:3 intTrapintA[],intN) {4 intsum =0; 5stack<int>St;6 7 for(inti =0; I <N;) {8 if(St.empty ()) {9St.push (i++);Ten}Else if(A[i] >=a[st.top ()]) { One intTMP =st.top (); A St.pop (); - if(!st.empty ()) sum + = (i-st.top ()-1) * (min (a[i], a[st.top ())-a[tmp]); -}Else { theSt.push (i++); - } - } - returnsum; + } -};Method II
Online there is another algorithm, the idea is to calculate the amount of rainfall can be stored in each location. Is gross position rainfall spread to each location. The rainfall at the current position is determined by its min (left maximum, right maximum). Rewrite it by thought.
1 classSolution {2 Public:3 intTrapintA[],intN) {4 if(n = =0)return 0;5 intsum =0; 6vector<int> Lfmost (N,0);7 8lfmost[0] = a[0];9 for(inti =1; I < n; ++i) {TenLfmost[i] = lfmost[i-1] > A[i-1] ? Lfmost[i-1]: A[i-1]; One } A - intmax = A[n-1]; - for(intj = N-2; J >=1; --j) { the if(A[j +1] > Max) max = A[j +1]; - ints = min (lfmost[j], max)-A[j]; - if(S >0) Sum + =s; - } + returnsum; - } +};