题解 | #接雨水问题#
接雨水问题
https://www.nowcoder.com/practice/31c1aed01b394f0b8b7734de0324e00f
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* max water
* @param arr int整型一维数组 the array
* @return long长整型
*/
public long maxWater (int[] arr) {
// write code here
long res = 0;
if(arr.length < 3){
return res;
}
// 指针定义
int left = 0;
int right = arr.length - 1;
// 中间区域的边界高度
int maxL = 0;
int maxR = 0;
while(left < right){
// 每次维护最新的最大边界
maxL = Math.max(arr[left],maxL);
maxR = Math.max(arr[right],maxR);
if(maxL < maxR){
res += maxL - arr[left++];
}else{
res += maxR - arr[right--];
}
}
return res;
}
}
