forked from Mickey0521/Codility
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StoneWall.java
38 lines (31 loc) · 1.1 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
package StoneWall;
import java.util.*;
class Solution {
public int solution(int[] H) {
// main idea: need to use "stack" to check when we need a new block
Stack<Integer> st = new Stack<>();
int numBlock =0;
// note: H[i] is the ith height of the wall
for(int i=0; i< H.length; i++){
// step 1: "stack is not empty" AND "from high to low"
// then, "pop" (it is the key point, be careful)
while( st.isEmpty()==false && st.peek() > H[i] ){
st.pop();
}
// step 2: if the stack is empty
if( st.isEmpty() ){
numBlock++; // add a block
st.push(H[i]); // push the height
}
// step 3: the height is the same: do nothing
else if( st.peek() == H[i] ){
}
// step 4: from low to high
else if( st.peek() < H[i] ){
numBlock++; // add a block
st.push(H[i]); // push the height
}
}
return numBlock;
}
}