42 Trapping rain water
https://leetcode.com/problems/trapping-rain-water/
class Solution {
public int trap(int[] height) {
int leftMax = 0;
int rightMax = 0;
int i = 0;
int j = height.length-1;
int sum = 0;
while (i <= j) {
leftMax = Math.max(leftMax, height[i]);
rightMax = Math.max(rightMax, height[j]);
if (leftMax < rightMax) {
// i左边的bar已经探索完了,leftMax确定是它的短板了,所以它能装的水就固定了
sum += leftMax - height[i++];
} else {
sum += rightMax - height[j--];
}
}
return sum;
}
}

Last updated