Class Solution
Hard
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.
Example 1:

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
Example 2:
Input: height = [4,2,0,3,2,5]
Output: 9
Constraints:
n == height.length1 <= n <= 2 * 1040 <= height[i] <= 105
To solve the “Trapping Rain Water” problem in Java with a Solution class, we can follow these steps:
- Define a
Solutionclass. - Define a method named
trapthat takes an array of integersheightas input and returns the amount of water it can trap after raining. - Initialize two pointers
leftandrightat the beginning and end of the array respectively. - Initialize two variables
leftMaxandrightMaxto keep track of the maximum height of bars encountered from the left and right directions respectively. - Iterate through the array using the two pointers:
- Update
leftMaxas the maximum ofleftMaxandheight[left]. - Update
rightMaxas the maximum ofrightMaxandheight[right]. - If
height[left] < height[right], calculate the water trapped at the current position usingleftMaxand subtract the height of the current bar. Moveleftpointer to the right. - Otherwise, calculate the water trapped at the current position using
rightMaxand subtract the height of the current bar. Moverightpointer to the left.
- Update
- Continue this process until the two pointers meet.
- Return the total amount of water trapped.
Here’s the implementation:
public class Solution {
public int trap(int[] height) {
int left = 0, right = height.length - 1;
int leftMax = 0, rightMax = 0;
int trappedWater = 0;
while (left < right) {
if (height[left] < height[right]) {
leftMax = Math.max(leftMax, height[left]);
trappedWater += leftMax - height[left];
left++;
} else {
rightMax = Math.max(rightMax, height[right]);
trappedWater += rightMax - height[right];
right--;
}
}
return trappedWater;
}
}
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.
-
Constructor Summary
Constructors -
Method Summary
-
Constructor Details
-
Solution
public Solution()
-
-
Method Details
-
trap
public int trap(int[] height)
-