-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path00042-trapping_rain_water.java
More file actions
43 lines (32 loc) · 926 Bytes
/
00042-trapping_rain_water.java
File metadata and controls
43 lines (32 loc) · 926 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// 42: Trapping Rain Water
// https://leetcode.com/problems/trapping-rain-water/
class Solution {
// SOLUTION
int trap(int[] height) {
int l = 0;
int r = height.length - 1;
int maxLeft = height[l];
int maxRight = height[r];
int result = 0;
while (l<r) {
if (maxLeft<=maxRight) {
l++;
maxLeft = Math.max(maxLeft, height[l]);
result += maxLeft - height[l];
} else {
r--;
maxRight = Math.max(maxRight, height[r]);
result += maxRight - height[r];
}
}
return result;
}
public static void main(String[] args) {
Solution o = new Solution();
// INPUT
int[] height = {4,2,0,3,2,5};
// OUTPUT
var result = o.trap(height);
System.out.println(result);
}
}