File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change 1+ // id: 42
2+ // Name: Trapping Rain Water
3+ // link: https://leetcode.com/problems/trapping-rain-water/description/
4+ // Difficulty: Hard
5+
6+ class Solution {
7+ public int trap (int [] height ) {
8+ int n = height .length ;
9+ int [] rightMaxes = new int [n ]; // maximum height at right of index i
10+ rightMaxes [n -1 ] = 0 ; // no element right
11+
12+ for (int i = n -2 ; i >= 0 ; i --) {
13+ rightMaxes [i ] = Math .max (height [i +1 ], rightMaxes [i +1 ]);
14+ }
15+
16+
17+ int result = 0 ;
18+ int leftMax = height [0 ];
19+ for (int i = 1 ; i < height .length -1 ; i ++) {
20+ // max right, max left
21+ int current = Math .min (rightMaxes [i ], leftMax ) - height [i ];
22+
23+ if (current > 0 ) result += current ;
24+
25+ leftMax = Math .max (leftMax , height [i ]);
26+ }
27+
28+ return result ;
29+ }
30+ }
You can’t perform that action at this time.
0 commit comments