|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 | 3 | /**
|
| 4 | + * 42. Trapping Rain Water |
4 | 5 | * 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 | 6 |
|
6 | 7 | For example,
|
7 | 8 | Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
|
8 | 9 |
|
9 |
| -
|
10 |
| - 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 | + 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. |
11 | 11 | */
|
| 12 | + |
12 | 13 | public class _42 {
|
13 | 14 |
|
14 | 15 | public int trap(int[] height) {
|
15 | 16 | int len = height.length;
|
16 |
| - if(len == 0){ |
| 17 | + if (len == 0) { |
17 | 18 | return 0;
|
18 | 19 | }
|
19 | 20 | int res = 0;
|
20 | 21 |
|
21 |
| - //first use DP to calculate out left and right arrays |
| 22 | + //first use DP to calculate left and right arrays |
22 | 23 | int[] left = new int[height.length];
|
23 | 24 | int[] right = new int[height.length];
|
24 | 25 |
|
25 | 26 | left[0] = height[0];
|
26 |
| - for(int i = 1; i < height.length; i++){ |
27 |
| - left[i] = Math.max(left[i-1], height[i]); |
| 27 | + for (int i = 1; i < height.length; i++) { |
| 28 | + left[i] = Math.max(left[i - 1], height[i]); |
28 | 29 | }
|
29 | 30 |
|
30 |
| - right[height.length-1] = height[height.length-1]; |
31 |
| - for(int i = height.length-2; i >= 0; i--){ |
32 |
| - right[i] = Math.max(right[i+1], height[i]); |
| 31 | + right[height.length - 1] = height[height.length - 1]; |
| 32 | + for (int i = height.length - 2; i >= 0; i--) { |
| 33 | + right[i] = Math.max(right[i + 1], height[i]); |
33 | 34 | }
|
34 | 35 |
|
35 |
| - for(int i = 1; i < height.length-1; i++){ |
| 36 | + for (int i = 1; i < height.length - 1; i++) { |
36 | 37 | res += Math.min(left[i], right[i]) - height[i];
|
37 | 38 | }
|
38 | 39 | return res;
|
|
0 commit comments