We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent e499d3b commit 7f519ceCopy full SHA for 7f519ce
src/main/java/com/TrapWater/TrapWater.java
@@ -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