/**
* To sum up total trapping water, we need to know how many water can be trapped by each bar after raining.
* The amount of trapping water for each bar is calculated by min(maxSeenLeft, maxSeenRight) - currentBarHeight.
* We will need an array to save the max height seen from right to left,
* and set the maxSeenLeft as 0, increase it each time we see and larger height,
* sum each bar's trapping water by min(maxSeenLeft, maxSeenRight) - currentBarHeight.
*/
public class Solution {
public int trap(int[] height) {
if (height == null || height.length == 0 || height.length == 1) {
return 0;
}
// Save the max height seen so far from right to left
int currMax = height[height.length-1];
int[] maxRight = new int[height.length];
maxRight[height.length-1] = currMax;
for (int i=height.length-2; i>=0; i--) {
if (height[i] > currMax) {
currMax = height[i];
}
maxRight[i] = currMax;
}
// From left to right, calculate each bar's trapping water
int maxWater = 0;
int maxLeft = 0;
for (int j=0; j<height.length; j++) {
maxWater += Math.max(Math.min(maxLeft, maxRight[j]) - height[j], 0);
// Update max height seen so far from left to right
if (height[j] > maxLeft) {
maxLeft = height[j];
}
}
return maxWater;
}
}
Leetcode 42. Trapping Rain Water
最新推荐文章于 2022-09-02 01:15:44 发布