File tree Expand file tree Collapse file tree 1 file changed +11
-12
lines changed Expand file tree Collapse file tree 1 file changed +11
-12
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
- public int trap (int [] height ) {
2
+ public int trap (int [] A ) {
3
+ Stack <Integer > stack = new Stack <Integer >();
4
+ int i = 0 ;
3
5
int maxWater = 0 ;
4
- for (int i =1 ;i <height .length -1 ;i ++) {
5
- int maxLeft = 0 ;
6
- int maxRight = 0 ;
7
-
8
- for (int j =i ;j <height .length ;j ++) {
9
- maxRight = Math .max (maxRight , height [j ]);
6
+
7
+ while (i < A .length ){
8
+ if (stack .isEmpty () || A [i ] <= A [stack .peek ()]){
9
+ stack .push (i ++);
10
10
}
11
-
12
- for (int j =i ;j >=0 ;j --) {
13
- maxLeft = Math .max (maxLeft , height [j ]);
11
+ else {
12
+ int bot = stack .pop ();
13
+ maxWater += stack .isEmpty () ? 0 :
14
+ (Math .min (A [stack .peek ()], A [i ]) - A [bot ]) * (i - stack .peek () - 1 );
14
15
}
15
-
16
- maxWater += Math .min (maxLeft , maxRight ) - height [i ];
17
16
}
18
17
19
18
return maxWater ;
You can’t perform that action at this time.
0 commit comments