-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday43_data_structure.cpp
More file actions
78 lines (67 loc) · 1.8 KB
/
day43_data_structure.cpp
File metadata and controls
78 lines (67 loc) · 1.8 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
71
72
73
74
75
76
77
78
/*
Good morning! Here's your coding interview problem for today.
This problem was asked by Amazon.
Implement a stack that has the following methods:
push(val), which pushes an element onto the stack
pop(), which pops off and returns the topmost element of the stack. If there are no elements in the stack, then it should throw an error or return null.
max(), which returns the maximum value in the stack currently. If there are no elements in the stack, then it should throw an error or return null.
Each method should run in constant time.
*/
#include <gtest/gtest.h>
#include <stack>
#include <stdexcept>
using namespace std;
/**
* Idea: We can use a second stack to track the max element at index i
*/
class MyStack
{
private:
stack<int> stck{};
stack<int> max_stck{};
public:
void push(int val)
{
stck.push(val);
if (max_stck.empty())
max_stck.push(val);
else
max_stck.push(std::max(max_stck.top(), val));
}
int pop()
{
if (stck.empty())
throw std::invalid_argument("Empty stack");
int val = stck.top();
stck.pop();
max_stck.pop();
return val;
}
int max()
{
if (max_stck.empty())
throw std::invalid_argument("Empty stack");
return max_stck.top();
}
};
TEST(STACK, stack)
{
MyStack stack;
stack.push(1);
EXPECT_EQ(stack.max(), 1);
stack.push(3);
EXPECT_EQ(stack.max(), 3);
stack.push(2);
EXPECT_EQ(stack.max(), 3);
EXPECT_EQ(stack.pop(), 2);
EXPECT_EQ(stack.max(), 3);
EXPECT_EQ(stack.pop(), 3);
EXPECT_EQ(stack.max(), 1);
stack.pop();
EXPECT_THROW(stack.max(), std::invalid_argument);
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}