Can someone help me understand how this two pointer solution to the rainwater capture interview problem works exactly? I don't understand the different steps involved and why they work. It would be very helpful if someone could walk me through it step by step.
The actual problem
function twoPointerRainwater(heights) {
let totalWater = 0;
let leftPointer = 0;
let rightPointer = heights.length - 1;
let leftBound = 0;
let rightBound = 0;
while (leftPointer < rightPointer) {
if (heights[leftPointer] <= heights[rightPointer]) {
leftBound = Math.max(heights[leftPointer], leftBound);
totalWater += leftBound - heights[leftPointer];
leftPointer++;
} else {
rightBound = Math.max(heights[rightPointer], rightBound);
totalWater += rightBound - heights[rightPointer];
rightPointer--;
}
}
return totalWater;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…