-
Notifications
You must be signed in to change notification settings - Fork 180
Expand file tree
/
Copy pathq042_TrapingRainWater.java
More file actions
48 lines (36 loc) · 1.08 KB
/
q042_TrapingRainWater.java
File metadata and controls
48 lines (36 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package leetcode_algorithm;
/**
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.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
*/
public class q042_TrapingRainWater {
public static void main(String[] args) {
int[] height = new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
System.out.println(new q042_TrapingRainWater().trap(height));
}
/**
* ½â·¨1 (ÍÆ¼ö½â·¨)
* @param height
* @return
*/
public int trap(int[] height) {
int a = 0;
int b = height.length - 1;
int max = 0;
int leftmax = 0;
int rightmax = 0;
while(a<=b){
leftmax = Math.max(leftmax, height[a]);
rightmax = Math.max(rightmax, height[b]);
if (leftmax < rightmax) {
max += (leftmax - height[a]);
a++;
}else {
max += (rightmax - height[b]);
b--;
}
}
return max;
}
}