|
1 | 1 | package com.thealgorithms.searches; |
2 | | - |
3 | 2 | /** |
4 | 3 | * Trapping Rainwater Problem |
5 | 4 | * Given an array of non-negative integers representing the height of bars, |
|
16 | 15 | */ |
17 | 16 | public class TrappingRainwater { |
18 | 17 |
|
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 | + } |
29 | 21 |
|
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; |
33 | 28 |
|
34 | 29 | while (left < right) { |
35 | 30 | if (height[left] < height[right]) { |
36 | 31 | if (height[left] >= leftMax) { |
37 | 32 | leftMax = height[left]; |
38 | 33 | } else { |
39 | | - trappedWater += leftMax - height[left]; |
| 34 | + result += leftMax - height[left]; |
40 | 35 | } |
41 | 36 | left++; |
42 | 37 | } else { |
43 | 38 | if (height[right] >= rightMax) { |
44 | 39 | rightMax = height[right]; |
45 | 40 | } else { |
46 | | - trappedWater += rightMax - height[right]; |
| 41 | + result += rightMax - height[right]; |
47 | 42 | } |
48 | 43 | right--; |
49 | 44 | } |
50 | 45 | } |
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; |
59 | 47 | } |
60 | 48 | } |
0 commit comments