|
| 1 | +/* |
| 2 | +Trapping Rain Water |
| 3 | +Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. |
| 4 | +*/ |
| 5 | + |
| 6 | +class Solution { |
| 7 | + public int trap(int[] arr) { |
| 8 | + int n = arr.length; |
| 9 | + |
| 10 | + // Edge case: If there are less than 3 bars, no water can be trapped |
| 11 | + if (n < 3) return 0; |
| 12 | + |
| 13 | + // ---------------------------- |
| 14 | + // Step 1: Create left max array |
| 15 | + // ---------------------------- |
| 16 | + // left[i] stores the maximum height of bar from index 0 to i. |
| 17 | + int[] left = new int[n]; |
| 18 | + left[0] = arr[0]; |
| 19 | + for (int i = 1; i < n; i++) { |
| 20 | + left[i] = Math.max(left[i - 1], arr[i]); |
| 21 | + } |
| 22 | + |
| 23 | + // ----------------------------- |
| 24 | + // Step 2: Create right max array |
| 25 | + // ----------------------------- |
| 26 | + // right[i] stores the maximum height of bar from index i to n-1. |
| 27 | + int[] right = new int[n]; |
| 28 | + right[n - 1] = arr[n - 1]; |
| 29 | + for (int i = n - 2; i >= 0; i--) { |
| 30 | + right[i] = Math.max(right[i + 1], arr[i]); |
| 31 | + } |
| 32 | + |
| 33 | + // ------------------------------------- |
| 34 | + // Step 3: Calculate trapped water at each index |
| 35 | + // ------------------------------------- |
| 36 | + // The water trapped at each position depends on: |
| 37 | + // min(max height on left, max height on right) - current height |
| 38 | + int totalWater = 0; |
| 39 | + for (int i = 0; i < n; i++) { |
| 40 | + totalWater += Math.min(left[i], right[i]) - arr[i]; |
| 41 | + } |
| 42 | + |
| 43 | + // Step 4: Return the total water trapped |
| 44 | + return totalWater; |
| 45 | + } |
| 46 | +} |
0 commit comments