一 双指针
public long maxWater (int[] arr) {
long res = 0;
if(arr==null) return 0;
// write code here
int left = 0;
int right = arr.length-1;
int maxLeft = arr[0];
int maxRight = arr[right];
while(left<right){
maxLeft = Math.max(maxLeft,arr[left]);
maxRight = Math.max(maxRight,arr[right]);
if(maxLeft<=maxRight){
if(maxLeft>arr[left]){
res += maxLeft-arr[left];
}
left++;
}else{
if(maxRight>arr[right]){
res += maxRight-arr[right];
}
right--;
}
}
return res;
}二 可以求出每个位置上方的水,然后加起来。 每个位置上方的水等于这个位置左边最大值和这个位置右边最大值的较小值,减去当前位置的水。

京公网安备 11010502036488号