public class Solution {
public int trap(int[] height) {
if (height == null || height.length < 3) {
return 0;
}
int result = 0;
int maxHeightIndex = 0;
for (int i = 0; i < height.length; i++) {
maxHeightIndex = height[i] > height[maxHeightIndex] ? i : maxHeightIndex;
}
int maxHeight = height[maxHeightIndex];
int left = 0;
int leftMaxHeight = height[0];
int right = height.length - 1;
int rightMaxHeight = height[height.length - 1];
while (left < maxHeightIndex) {
leftMaxHeight = Math.max(leftMaxHeight, height[left]);
result += leftMaxHeight - height[left];
left++;
}
while (right > maxHeightIndex) {
rightMaxHeight = Math.max(rightMaxHeight, height[right]);
result += rightMaxHeight - height[right];
right--;
}
return result;
}
}