public static int water3(int []arr){
int water=0;
if(arr==null||arr.length<=1)
return 0;
int largestLeft=0,largestRight=0;
//分别保存左右两边最大值
int left=0,right=arr.length-1;
while(left<right)
{
largestLeft=Math.max(arr[left], largestLeft);
largestRight=Math.max(arr[right], largestRight);
//获得左右两边最大值
if(largestLeft>largestRight)
{
//如果左边最大值大于右边则右指针向移动
water+=largestRight-arr[right--];
}
else {
//否则左指针向右移动
water+=largestLeft-arr[left++];
}
}
return water;
}
//基于上面思想,自己写的
public static int chushui(int[] arr) {
int sum = 0;
int left = 0, right = arr.length - 1;
int leftMax = arr[left], rightMax = arr[right];
while (left < right) {
if (leftMax > rightMax) {
if (arr[right] <= rightMax)
sum += (rightMax - arr[right]);
else
rightMax = arr[right];
right--;
} else {
if (arr[left] <= leftMax) {
sum = sum + (leftMax - arr[left]);
} else {
leftMax = arr[left];
}
left++;
}
}
return sum;
}