Skip to content

Commit 7f519ce

Browse files
committed
Trap water Solution
1 parent e499d3b commit 7f519ce

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public int trap(int[] height) {
3+
int n = height.length;
4+
if (n == 0) return 0;
5+
6+
int[] left = new int[n];
7+
int[] right = new int[n];
8+
int storedWater = 0;
9+
10+
// Fill left array
11+
left[0] = height[0];
12+
for (int i = 1; i < n; i++) {
13+
left[i] = Math.max(left[i - 1], height[i]);
14+
}
15+
16+
// Fill right array
17+
right[n - 1] = height[n - 1];
18+
for (int i = n - 2; i >= 0; i--) {
19+
right[i] = Math.max(right[i + 1], height[i]);
20+
}
21+
22+
// Calculate trapped water
23+
for (int i = 0; i < n; i++) {
24+
int minHeight = Math.min(left[i], right[i]);
25+
storedWater += minHeight - height[i];
26+
}
27+
28+
return storedWater;
29+
}
30+
}

0 commit comments

Comments
 (0)