题解 | #接雨水问题#
接雨水问题
http://www.nowcoder.com/practice/31c1aed01b394f0b8b7734de0324e00f
package org.example.test; public class WaterTest { public long maxWater(int[] arr) { // write code here int maxLeft = 0; int maxRight = 0; int left = 0; int right = arr.length - 1; long ans = 0; while (left < right) { if (arr[left] < arr[right]) { if (arr[left] > maxLeft) { maxLeft = arr[left]; } else { ans += (maxLeft - arr[left]); } ++left; } else { if (arr[right] > maxRight) { maxRight = arr[right]; } else { ans += (maxRight - arr[right]); } --right; } } return ans; } }
算法 文章被收录于专栏
数据结构和算法