|
| 1 | + |
| 2 | +// O(N^2) solution |
| 3 | +class Solution { |
| 4 | + public int trap(int[] height) { |
| 5 | + int total = 0; |
| 6 | + for (int i=1; i<height.length; i++) { |
| 7 | + int cur_left= max(height, 0, i); |
| 8 | + //System.out.println(cur_left); |
| 9 | + int cur_right = max(height, i, height.length-1); |
| 10 | + //System.out.println(cur_right); |
| 11 | + int cur_max = Math.min(cur_left, cur_right); |
| 12 | + total = total + cur_max - height[i]; |
| 13 | + } |
| 14 | + return total; |
| 15 | + } |
| 16 | + |
| 17 | + public int max(int[] height, int left, int right) { |
| 18 | + int max = 0; |
| 19 | + for (int i=left; i<=right; i++) { |
| 20 | + if (height[i] > max) { |
| 21 | + max = height[i]; |
| 22 | + } |
| 23 | + } |
| 24 | + return max; |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +// O(N) time, O(N) space |
| 29 | +class Solution { |
| 30 | + public int trap(int[] height) { |
| 31 | + int[] left = precomputeLeft(height); |
| 32 | + int[] right = preComputeRight(height); |
| 33 | + int total = 0; |
| 34 | + for (int i=0; i<height.length; i++) { |
| 35 | + |
| 36 | + total += Math.min(left[i], right[i]) - height[i]; |
| 37 | + } |
| 38 | + return total; |
| 39 | + } |
| 40 | + |
| 41 | + public int[] precomputeLeft(int[] height) { |
| 42 | + int[] res = new int[height.length]; |
| 43 | + if (height.length == 0) { |
| 44 | + return res; |
| 45 | + } |
| 46 | + res[0] = height[0]; |
| 47 | + for (int i=1; i<height.length; i++) { |
| 48 | + res[i] = Math.max(res[i-1], height[i]); |
| 49 | + } |
| 50 | + return res; |
| 51 | + } |
| 52 | + |
| 53 | + public int[] preComputeRight(int[] height) { |
| 54 | + int[] res = new int[height.length]; |
| 55 | + if (height.length == 0) { |
| 56 | + return res; |
| 57 | + } |
| 58 | + res[height.length - 1] = height[height.length -1]; |
| 59 | + for (int i=height.length - 2; i>= 0; i--) { |
| 60 | + res[i] = Math.max(res[i+1], height[i]); |
| 61 | + } |
| 62 | + return res; |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +// O(N) time. O(1) space using lower envelope technique |
1 | 67 | class Solution {
|
2 | 68 | public int trap(int[] height) {
|
3 | 69 | int leftMax = 0;
|
|
0 commit comments