public static void main(String[] args) {
// int[] ints = {0,0,0,1,0,0};
int[] ints = {2,1,5,1,2};
// int[] ints = {5, 1, 1, 5};
// int[] ints = {1, 3, 2, 4, 1};
System.out.println(getWater(ints));
}
public static int getWater(int[] arr) {
if (null == arr) {
return 0;
}
int count = 0;
for (int i = 0; i < arr.length; i++) {
int leftMax = (i == 0) ? 0 : max(arr, 0, i);
int rightMax = (i == arr.length - 1) ? 0 : max(arr, i + 1, arr.length);
int max = Math.min(leftMax, rightMax);
int water = max - arr[i];
if (water > 0) {
count += water;
}
}
return count;
}
public static int max(int[] arr, int start, int end) {
if (null == arr || start < 0 || end > arr.length || end < start) {
return 0;
}
int max = arr[start];
for (int i = start + 1; i < end; i++) {
max = Math.max(max, arr[i]);
}
return max;
}