Skip to content

Commit 607edf0

Browse files
authored
Update readme.md
1 parent bb16cde commit 607edf0

File tree

1 file changed

+43
-1
lines changed
  • src/main/java/g0001_0100/s0042_trapping_rain_water

1 file changed

+43
-1
lines changed

src/main/java/g0001_0100/s0042_trapping_rain_water/readme.md

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,46 @@ Given `n` non-negative integers representing an elevation map where the width of
2424

2525
* `n == height.length`
2626
* <code>1 <= n <= 2 * 10<sup>4</sup></code>
27-
* <code>0 <= height[i] <= 10<sup>5</sup></code>
27+
* <code>0 <= height[i] <= 10<sup>5</sup></code>
28+
29+
To solve the "Trapping Rain Water" problem in Java with a `Solution` class, we can follow these steps:
30+
31+
1. Define a `Solution` class.
32+
2. Define a method named `trap` that takes an array of integers `height` as input and returns the amount of water it can trap after raining.
33+
3. Initialize two pointers `left` and `right` at the beginning and end of the array respectively.
34+
4. Initialize two variables `leftMax` and `rightMax` to keep track of the maximum height of bars encountered from the left and right directions respectively.
35+
5. Iterate through the array using the two pointers:
36+
- Update `leftMax` as the maximum of `leftMax` and `height[left]`.
37+
- Update `rightMax` as the maximum of `rightMax` and `height[right]`.
38+
- If `height[left] < height[right]`, calculate the water trapped at the current position using `leftMax` and subtract the height of the current bar. Move `left` pointer to the right.
39+
- Otherwise, calculate the water trapped at the current position using `rightMax` and subtract the height of the current bar. Move `right` pointer to the left.
40+
6. Continue this process until the two pointers meet.
41+
7. Return the total amount of water trapped.
42+
43+
Here's the implementation:
44+
45+
```java
46+
public class Solution {
47+
public int trap(int[] height) {
48+
int left = 0, right = height.length - 1;
49+
int leftMax = 0, rightMax = 0;
50+
int trappedWater = 0;
51+
52+
while (left < right) {
53+
if (height[left] < height[right]) {
54+
leftMax = Math.max(leftMax, height[left]);
55+
trappedWater += leftMax - height[left];
56+
left++;
57+
} else {
58+
rightMax = Math.max(rightMax, height[right]);
59+
trappedWater += rightMax - height[right];
60+
right--;
61+
}
62+
}
63+
64+
return trappedWater;
65+
}
66+
}
67+
```
68+
69+
This implementation provides a solution to the "Trapping Rain Water" problem in Java. It calculates the amount of water that can be trapped between bars by using two pointers to track the left and right boundaries and two variables to track the maximum heights of bars encountered from the left and right directions.

0 commit comments

Comments
 (0)