Given an array of non-negative integers representing building heights, calculate the total volume of water trapped on the rooftops after heavy rain.
Explanation: Step-by-step: Given the input [0,1,0,2,1,0,1,3,2,1,2,1], we first initialize two pointers, left and right, to the start and end of the array respectively. We also initialize two variables, maxLeft and maxRight, to store the maximum height of the left and right sides of the array. We then iterate through the array from left to right, and for each element, we calculate the water trapped by taking the minimum of maxLeft and maxRight, and subtracting the current height. We add this value to the total water trapped. We repeat this process for the right to left iteration. The final output is the total water trapped, which is 6.
Explanation: Step-by-step: Given the input [4,2,0,3,2,5], we first initialize two pointers, left and right, to the start and end of the array respectively. We also initialize two variables, maxLeft and maxRight, to store the maximum height of the left and right sides of the array. We then iterate through the array from left to right, and for each element, we calculate the water trapped by taking the minimum of maxLeft and maxRight, and subtracting the current height. We add this value to the total water trapped. We repeat this process for the right to left iteration. The final output is the total water trapped, which is 9.
Analyze constraints and compute optimal solutions step-by-step.
No dry run loaded.
🚀 Practice this problem
Run code, get AI hints & track streak