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 @@ -4,21 +4,20 @@ public int trap(int[] height) {
4
4
return 0 ;
5
5
}
6
6
7
+ int leftMax = 0 , rightMax = 0 ;
8
+ int left = 0 , right = height .length - 1 ;
7
9
int water = 0 ;
8
- int leftMax = height [0 ], rightTallest = height [height .length - 1 ];
9
- int [] leftMaxes = new int [height .length ];
10
10
11
- for (int i = 0 ; i < height .length ; i ++) {
12
- leftMax = Math .max (leftMax , height [i ]);
13
- leftMaxes [i ] = leftMax ;
14
- }
15
-
16
- for (int i = height .length - 1 ; i >= 0 ; i --) {
17
- rightTallest = Math .max (rightTallest , height [i ]);
11
+ while (left < right ) {
12
+ leftMax = Math .max (leftMax , height [left ]);
13
+ rightMax = Math .max (rightMax , height [right ]);
18
14
19
- int leftTallest = Math .min (rightTallest , leftMaxes [i ]);
20
- if (leftTallest > height [i ]) {
21
- water += leftTallest - height [i ];
15
+ if (leftMax < rightMax ) {
16
+ water += leftMax - height [left ];
17
+ ++left ;
18
+ } else {
19
+ water += rightMax - height [right ];
20
+ --right ;
22
21
}
23
22
}
24
23
You can’t perform that action at this time.
0 commit comments