-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathTrappingRainwater.java
More file actions
36 lines (32 loc) · 937 Bytes
/
TrappingRainwater.java
File metadata and controls
36 lines (32 loc) · 937 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
//https://leetcode.com/problems/trapping-rain-water/
class Solution {
//T(n): O(n)
//S(n): O(n)
public int trap(int[] height) {
int n = height.length;
int[] left = new int[n];
int[] right = new int[n];
left[0] = height[0];
for (int i = 1; i < n; i++) {
if (height[i] > left[i - 1]) {
left[i] = height[i];
} else {
left[i] = left[i - 1];
}
}
right[n - 1] = height[n - 1];
for (int i = n - 2; i >= 0; i--) {
if (height[i] > right[i + 1]) {
right[i] = height[i];
} else {
right[i] = right[i + 1];
}
}
int sum = 0;
for (int i = 0; i < n; i++) {
height[i] = Math.min(left[i], right[i]) - height[i];
sum += height[i];
}
return sum;
}
}