-
Notifications
You must be signed in to change notification settings - Fork 13
/
StoneWall.cpp
69 lines (63 loc) · 1.59 KB
/
StoneWall.cpp
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
#include <stack>
// #define debug
#ifdef debug
#define LOG(X) cout << X << endl
#else
#define LOG(X) (void)0
#endif
int solution(vector<int> &H) {
if(H.size() == 1)
return 1;
int count = 0;
stack<int> W;
int current_h = 0;
for(auto h : H) {
if(W.empty()) {
W.push(h);
current_h = h;
LOG(current_h);
count++;
} else if(current_h == h) {
continue;
} else if(current_h < h) {
LOG(h - current_h);
W.push(h - current_h);
current_h = h;
count++;
} else {
while(!W.empty() && current_h > h) {
current_h -= W.top();
W.pop();
}
if(!W.empty() && current_h < h) {
LOG(h - current_h);
W.push(h - current_h);
current_h = h;
count++;
}
if(W.empty()) {
W.push(h);
current_h = h;
LOG(current_h);
count++;
}
}
}
return count;
}
// ref: https://molchevskyi.medium.com/best-solutions-for-codility-lessons-lesson-7-stacks-and-queues-ef1415898cb
int solution2(const vector<int> &v) {
std::stack<int> stack;
int stones = 0;
for (auto height : v) {
while (!stack.empty() && stack.top() > height) {
stack.pop();
}
if (!stack.empty() && stack.top() == height) {
continue;
}
stones++;
stack.push(height);
}
return stones;
}