|
| 1 | +package Leetcode; |
| 2 | +/* |
| 3 | + * Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. |
| 4 | +
|
| 5 | +
|
| 6 | +Example 1: |
| 7 | +
|
| 8 | +
|
| 9 | +Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] |
| 10 | +Output: 6 |
| 11 | +Explanation: The above elevation map (black section) 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. |
| 12 | +Example 2: |
| 13 | +
|
| 14 | +Input: height = [4,2,0,3,2,5] |
| 15 | +Output: 9 |
| 16 | +
|
| 17 | +Runtime: 1 ms, faster than 99.76% of Java online submissions for Trapping Rain Water. |
| 18 | +Memory Usage: 48.3 MB, less than 76.32% of Java online submissions for Trapping Rain Water. |
| 19 | + * |
| 20 | + */ |
| 21 | +public class TappingRainWater { |
| 22 | + |
| 23 | + public static void main(String[] args) { |
| 24 | + var trw = new TappingRainWater(); |
| 25 | + System.out.println(trw.trap(new int[]{0,1,0,2,1,0,1,3,2,1,2,1})); |
| 26 | + } |
| 27 | + |
| 28 | + public int trap(int[] height) { |
| 29 | + int ans = 0; int left = 0; int right = height.length-1; |
| 30 | + int leftmax =0; |
| 31 | + int rightmax =0; |
| 32 | + while(left<right){ |
| 33 | + if(height[left]<height[right]){ |
| 34 | + if(height[left]>= leftmax){ |
| 35 | + leftmax=height[left]; |
| 36 | + } |
| 37 | + else{ |
| 38 | + ans+=(leftmax-height[left]); |
| 39 | + } |
| 40 | + left++; |
| 41 | + } |
| 42 | + else{ |
| 43 | + |
| 44 | + if(height[right]>=rightmax){ |
| 45 | + rightmax=height[right]; |
| 46 | + } |
| 47 | + else{ans+=(rightmax-height[right]);} |
| 48 | + right--; |
| 49 | + } |
| 50 | + } |
| 51 | + return ans; |
| 52 | + } |
| 53 | +} |
0 commit comments