-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrap.java
More file actions
70 lines (48 loc) · 1.5 KB
/
Copy pathTrap.java
File metadata and controls
70 lines (48 loc) · 1.5 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package org.example;
import java.util.Stack;
public class Trap {
class Unit {
int index;
int height;
public Unit(int index,int height) {
this.index = index;
this.height = height;
}
}
public int trap(int[] height) {
if (height.length == 0) {
return 0;
}
Stack<Unit> stack = new Stack<>();
stack.push(new Unit(0, height[0]));
int total = 0;
for (int i = 1; i < height.length; i++) {
if (stack.isEmpty()) {
stack.push(new Unit(i, height[i]));
continue;
}
Unit left = stack.peek();
int currHeight = height[i];
if (currHeight < left.height) {
} else {
int rightIndex = i;
System.out.println("left = " + left.index + ", right = " + rightIndex);
int sum = 0;
for (int j = left.index + 1; j < rightIndex; j++) {
// bug
// sum = sum + height[j] - left.height;
sum = sum + left.height - height[j];
}
total += sum;
stack.pop();
}
}
return total;
}
public static void main(String[] args) {
Trap trapSolver = new Trap();
int[] height = {0,1,0,2,1,0,1,3,2,1,2,1};
int result = trapSolver.trap(height);
System.out.println("Trapped water: " + result);
}
}