-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathStoneWall.java
42 lines (37 loc) · 1.16 KB
/
StoneWall.java
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
/*
Cover "Manhattan skyline" using the minimum number of rectangles.
*/
import java.util.*;
// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");
class Solution {
public int solution(int[] H) {
Stack<Integer> stack = new Stack<>();
int count = 0;
for (int i = 0; i < H.length; i++) {
if (stack.isEmpty()) {
stack.push(H[i]);
count++;
} else {
int curHeight = stack.peek();
if (H[i] == curHeight) {
continue;
} else if (H[i] < curHeight) {
while (!stack.isEmpty() && stack.peek() > H[i]) {
stack.pop();
}
if (!stack.isEmpty() && H[i] == stack.peek()) {
continue;
} else {
stack.push(H[i]);
count++;
}
} else {
stack.push(H[i]);
count++;
}
}
}
return count;
}
}