|
| 1 | +import java.util.Stack; |
| 2 | + |
| 3 | +/** |
| 4 | + * Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. |
| 5 | + * <p> |
| 6 | + * For example, |
| 7 | + * Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. |
| 8 | + * <p> |
| 9 | + * The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image! |
| 10 | + * <p> |
| 11 | + * Created by drfish on 6/7/2017. |
| 12 | + */ |
| 13 | +public class _042TrappingRainWater { |
| 14 | + public int trap(int[] height) { |
| 15 | + if (height == null) { |
| 16 | + return 0; |
| 17 | + } |
| 18 | + int leftIndex = 0; |
| 19 | + int rightIndex = height.length - 1; |
| 20 | + int leftMax = 0; |
| 21 | + int rightMax = 0; |
| 22 | + int result = 0; |
| 23 | + |
| 24 | + while (leftIndex <= rightIndex) { |
| 25 | + if (height[leftIndex] <= height[rightIndex]) { |
| 26 | + if (height[leftIndex] >= leftMax) { |
| 27 | + leftMax = height[leftIndex]; |
| 28 | + } else { |
| 29 | + result += leftMax - height[leftIndex]; |
| 30 | + } |
| 31 | + leftIndex++; |
| 32 | + } else { |
| 33 | + if (height[rightIndex] >= rightMax) { |
| 34 | + rightMax = height[rightIndex]; |
| 35 | + } else { |
| 36 | + result += rightMax - height[rightIndex]; |
| 37 | + } |
| 38 | + rightIndex--; |
| 39 | + } |
| 40 | + } |
| 41 | + return result; |
| 42 | + } |
| 43 | + |
| 44 | + public static void main(String[] args) { |
| 45 | + _042TrappingRainWater solution = new _042TrappingRainWater(); |
| 46 | + int[] height = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; |
| 47 | + assert 6 == solution.trap(height); |
| 48 | + assert 0 == solution.trap(new int[]{0, 2, 0}); |
| 49 | + } |
| 50 | +} |
0 commit comments