Skip to content

Commit 6d42fda

Browse files
committed
fix: add package and resolve checkstyle errors for TrappingRainwater.java
1 parent b9a0653 commit 6d42fda

File tree

1 file changed

+12
-24
lines changed

1 file changed

+12
-24
lines changed
Lines changed: 12 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
package com.thealgorithms.searches;
2-
32
/**
43
* Trapping Rainwater Problem
54
* Given an array of non-negative integers representing the height of bars,
@@ -16,45 +15,34 @@
1615
*/
1716
public class TrappingRainwater {
1817

19-
/**
20-
* Calculates the total trapped rainwater.
21-
*
22-
* @param height an array representing elevation map
23-
* @return total units of water trapped
24-
*/
25-
public static int trap(int[] height) {
26-
if (height == null || height.length == 0) {
27-
return 0;
28-
}
18+
private TrappingRainwater() {
19+
throw new UnsupportedOperationException("Utility class");
20+
}
2921

30-
int left = 0, right = height.length - 1;
31-
int leftMax = 0, rightMax = 0;
32-
int trappedWater = 0;
22+
public static int trap(int[] height) {
23+
int left = 0;
24+
int right = height.length - 1;
25+
int leftMax = 0;
26+
int rightMax = 0;
27+
int result = 0;
3328

3429
while (left < right) {
3530
if (height[left] < height[right]) {
3631
if (height[left] >= leftMax) {
3732
leftMax = height[left];
3833
} else {
39-
trappedWater += leftMax - height[left];
34+
result += leftMax - height[left];
4035
}
4136
left++;
4237
} else {
4338
if (height[right] >= rightMax) {
4439
rightMax = height[right];
4540
} else {
46-
trappedWater += rightMax - height[right];
41+
result += rightMax - height[right];
4742
}
4843
right--;
4944
}
5045
}
51-
52-
return trappedWater;
53-
}
54-
55-
// Example test
56-
public static void main(String[] args) {
57-
int[] height = {4, 2, 0, 3, 2, 5};
58-
System.out.println("Total trapped water: " + trap(height)); // Output: 9
46+
return result;
5947
}
6048
}

0 commit comments

Comments
 (0)