Skip to content

Commit 5a5bcd9

Browse files
committed
Add Trapping Rainwater problem implementation (Two Pointer Approach)
1 parent bb6385e commit 5a5bcd9

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package com.thealgorithms.searches;
2+
3+
/**
4+
* Trapping Rainwater Problem
5+
* Given an array of non-negative integers representing the height of bars,
6+
* compute how much water it can trap after raining.
7+
*
8+
* Example:
9+
* Input: [4,2,0,3,2,5]
10+
* Output: 9
11+
*
12+
* Time Complexity: O(n)
13+
* Space Complexity: O(1)
14+
*/
15+
public class TrappingRainwater {
16+
17+
/**
18+
* Calculates the total trapped rainwater.
19+
*
20+
* @param height an array representing elevation map
21+
* @return total units of water trapped
22+
*/
23+
public static int trap(int[] height) {
24+
if (height == null || height.length == 0) {
25+
return 0;
26+
}
27+
28+
int left = 0, right = height.length - 1;
29+
int leftMax = 0, rightMax = 0;
30+
int trappedWater = 0;
31+
32+
while (left < right) {
33+
if (height[left] < height[right]) {
34+
if (height[left] >= leftMax) {
35+
leftMax = height[left];
36+
} else {
37+
trappedWater += leftMax - height[left];
38+
}
39+
left++;
40+
} else {
41+
if (height[right] >= rightMax) {
42+
rightMax = height[right];
43+
} else {
44+
trappedWater += rightMax - height[right];
45+
}
46+
right--;
47+
}
48+
}
49+
50+
return trappedWater;
51+
}
52+
53+
// Example test
54+
public static void main(String[] args) {
55+
int[] height = {4, 2, 0, 3, 2, 5};
56+
System.out.println("Total trapped water: " + trap(height)); // Output: 9
57+
}
58+
}

0 commit comments

Comments
 (0)