File tree Expand file tree Collapse file tree 1 file changed +11
-11
lines changed Expand file tree Collapse file tree 1 file changed +11
-11
lines changed Original file line number Diff line number Diff line change @@ -5,21 +5,21 @@ public int trap(int[] height) {
5
5
}
6
6
7
7
int water = 0 ;
8
- int [] leftMax = new int [height .length ], rightMax = new int [height .length ];
8
+ int leftMax = height [0 ], rightTallest = height [height .length - 1 ];
9
+ int [] leftMaxes = new int [height .length ];
9
10
10
- leftMax [0 ] = height [0 ];
11
- rightMax [rightMax .length - 1 ] = height [height .length - 1 ];
12
-
13
- for (int i = 1 ; i < height .length ; i ++) {
14
- leftMax [i ] = Math .max (height [i ], leftMax [i - 1 ]);
11
+ for (int i = 0 ; i < height .length ; i ++) {
12
+ leftMax = Math .max (leftMax , height [i ]);
13
+ leftMaxes [i ] = leftMax ;
15
14
}
16
15
17
- for (int i = height .length - 2 ; i >= 0 ; i --) {
18
- rightMax [i ] = Math .max (height [i ], rightMax [i + 1 ]);
19
- }
16
+ for (int i = height .length - 1 ; i >= 0 ; i --) {
17
+ rightTallest = Math .max (rightTallest , height [i ]);
20
18
21
- for (int i = 1 ; i < height .length - 1 ; i ++) {
22
- water += Math .min (leftMax [i ], rightMax [i ]) - height [i ];
19
+ int leftTallest = Math .min (rightTallest , leftMaxes [i ]);
20
+ if (leftTallest > height [i ]) {
21
+ water += leftTallest - height [i ];
22
+ }
23
23
}
24
24
25
25
return water ;
You can’t perform that action at this time.
0 commit comments