package 数组;
/**
* https://leetcode-cn.com/problems/trapping-rain-water/solution/
* @author Huangyujun
* 思路: 一个水柱A能接到多少水,取决于左右两侧最低的柱子与当前水柱A 的高度差(单元水量),同时要注意的是左侧的柱子的最大值,即可高度差最大值
* 例如首先左边柱子比较低,找到左边(在比较低的范围找到一个最大值 left_max)获取最大高度差水量
*/
public class _42_接雨水 {
public int trap(int[] height) {
int left = 0, right = height.length - 1;
int ans = 0;
int left_max = 0, right_max = 0;
while (left < right) {
if (height[left] < height[right]) { // 需要找小的:(目的:去获取那个小柱子中的最大值)
if (height[left] >= left_max) {
left_max = height[left];
} else {
ans += (left_max - height[left]);
}
++left;
} else {
if (height[right] >= right_max) {
right_max = height[right];
} else {
ans += (right_max - height[right]);
}
--right;
}
}
return ans;
}
}