public class Solution {
public int trap(int[] A) {
if(A == null || A.length < 2) {
return 0;
}
int area = 0;
int maxInd = findMaxInd(A);
int leftMax = A[0];
for(int i = 1; i < maxInd; i++) {
leftMax = Math.max(leftMax, A[i]);
area += (leftMax - A[i]);
}
int rightMax = A[A.length - 1];
for(int i = A.length - 2; i > maxInd; i--) {
rightMax = Math.max(rightMax, A[i]);
area += (rightMax - A[i]);
}
return area;
}
private int findMaxInd(int[] A) {
int max = A[0];
int ind = 0;
for(int i = 1; i < A.length; i++) {
if(max < A[i]) {
max = A[i];
ind = i;
}
}
return ind;
}
}
Time: O(n)
Space: O(1)