题解 | #接雨水问题#
接雨水问题
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
if (arr == null || arr.length < 3) {
return 0;
}
int l = 0;
int r = arr.length - 1;
int maxL = 0;
int maxR = 0;
int res = 0;
while (l < r) {
maxL = Math.max(maxL, arr[l]);
maxR = Math.max(maxR, arr[r]);
if (maxR > maxL) {
res += maxL - arr[l++];
} else {
res += maxR - arr[r--];
}
}
return res;
}
}
