42. Trapping Rain Water
Intitution
Complexity
Space Complexity
Time Complexity
Code
public int trap(int[] elevationHeights) {
int n = elevationHeights.length;
// Array to store the maximum height to the right of each bar
int[] maxHeightToRight = new int[n];
int maxSoFar = 0;
// Traverse from right to left to fill maxHeightToRight
for (int i = n - 1; i >= 0; --i) {
maxHeightToRight[i] = maxSoFar;
maxSoFar = Math.max(elevationHeights[i], maxSoFar);
}
int totalTrappedWater = 0;
maxSoFar = 0; // Reuse for max height to the left
// Traverse from left to right to compute trapped water
for (int i = 0; i < n; ++i) {
// Water that can be stored at current index
int waterAtCurrent = Math.min(maxSoFar, maxHeightToRight[i]) - elevationHeights[i];
// Only count if it's a positive amount of water
if (waterAtCurrent > 0) {
totalTrappedWater += waterAtCurrent;
}
maxSoFar = Math.max(elevationHeights[i], maxSoFar);
}
return totalTrappedWater;
}
Last updated