题解 | 接雨水问题
接雨水问题
https://www.nowcoder.com/practice/31c1aed01b394f0b8b7734de0324e00f
import java.util.*; public class Solution { /** * 两边就像是两堵墙,能存多少水有较矮的那堵墙决定,高的强起到的作用就是挡水的作用 * 维护两个指针,同时维护两个最大值,左边和右边的最大值, * 如果右边最大值比左边最大值大,左边往右走,同时计算左边最大值,左边最大值与左边当前值的差就是当前位置能存多少水 * 如果左边最大值比右边最大值大,右边往左走,同时计算右边最大值,右边最大值与右边当前值的差就是当前位置能存多少水 * * @param arr * @return */ public long maxWater(int[] arr) { if (arr == null || arr.length <= 2) { return 0L; } int left = 0; int right = arr.length - 1; int maxLeft = 0; int maxRight = 0; int area = 0; while (left < right) { maxLeft = Math.max(maxLeft, arr[left]); maxRight = Math.max(maxRight, arr[right]); if (maxLeft < maxRight) { area += maxLeft - arr[left]; left++; } else { area += maxRight - arr[right]; right--; } } return area; } }