Description:
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Analysis:
Use volume[i]
to denote the amount of water in the
i
i
i-th position;
Use height[i]
to denote the height of bar in the
i
i
i-th position;
Use leftMaximumDp[i]
to denote the maximum height of a position that is before the
i
i
i-th position;
Use rightMaximumDp[i]
to denote the maximum height of a position that is after the
i
i
i-th position.
int minMaximum = Math.min(leftMaximumDp[i], rightMaximumDp[i]);
volume[i] = (minMaximum - height[i] >= 0 ? minMaximum - height[i] : 0);
Code:
class Solution {
public int trap(int[] height) {
int N = height.length;
int[] leftMaximumDp = new int[N];
int[] rightMaximumDp = new int[N];
for(int i = 1; i < N; i++) {
leftMaximumDp[i] = Math.max(leftMaximumDp[i-1], height[i-1]);
}
for(int i = N-2; i >=0; i--) {
rightMaximumDp[i] = Math.max(rightMaximumDp[i+1], height[i+1]);
}
int volume = 0;
for(int i = 0; i< N; i++) {
int leftMaximum = leftMaximumDp[i];
int rightMaximum = rightMaximumDp[i];
int minMaximum = Math.min(leftMaximum, rightMaximum);
volume += (minMaximum - height[i] >= 0 ? minMaximum - height[i] : 0);
}
return volume;
}
}