Given an array height
representing the height of blocks, calculate how much water can be trapped after rainfall. Water can only be trapped between blocks if there is a taller block on both the left and the right of the current block.
Find the total amount of water that can be trapped between the blocks.
For each block, the water it can trap is determined by:
min(leftMax, rightMax) - height[i]
Where:
leftMax
is the maximum height of blocks to the left of the current block.rightMax
is the maximum height of blocks to the right of the current block.leftMax
.rightMax
.i
as:water[i] = min(leftMax[i], rightMax[i]) - height[i]
height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
[0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3]
[3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 1]
[0, 0, 1, 0, 1, 2, 1, 0, 0, 1, 0, 0]
6
Output:
6
Input:
height = [4, 2, 0, 3, 2, 5]
Output:
9
Explanation:
Water trapped at each block: [0, 2, 4, 1, 2, 0]
Total water trapped = 9
.
Input:
height = [1, 0, 2]
Output:
1
Explanation:
Water trapped at each block: [0, 1, 0]
Total water trapped = 1
.
Input:
height = [0, 1, 0, 1, 0]
Output:
0
Explanation:
No water is trapped because no block has taller blocks on both sides.
Input:
height = [3, 0, 0, 2, 0, 4]
Output:
10
Explanation:
Water trapped at each block: [0, 3, 3, 1, 3, 0]
Total water trapped = 10
.
1 <= height.length <= 10^5
0 <= height[i] <= 10^4
leftMax
, rightMax
, and total water trapped.leftMax
and rightMax
arrays.For an optimized version, we can reduce space complexity to O(1) using two-pointer technique.
https://leetcode.com/problems/trapping-rain-water/
Loading component...
Loading component...
Main Function is not defined.
public static int trap(vector<int>& height){
vector<int>prefix;
vector<int>suffix;
int max = *height.begin();
for(auto i = height.begin(); i< height.end();i++){
if(*i > max){
max = *i;
}
suffix.push_back(max);
}
reverse(suffix.begin(),suffix.end());
int sum =0;
for(int i = 0; i< height.size();i++){
int n = min(prefix[i],suffix[i]-height[i]);
if(n<0){
n = 0;
}
sum = sum + n;
}
return sum;
}//function end
Utility Function is not required.