[LeetCode] Design a Stack With Increment Operation

1381. Design a Stack With Increment Operation

Design a stack which supports the following operations.

Implement the CustomStack class:

  • CustomStack(int maxSize) Initializes the object with maxSize which is the maximum number of elements in the stack or do nothing if the stack reached the maxSize.
  • void push(int x) Adds x to the top of the stack if the stack hasn’t reached the maxSize.
  • int pop() Pops and returns the top of stack or -1 if the stack is empty.
  • void inc(int k, int val) Increments the bottom k elements of the stack by val. If there are less than k elements in the stack, just increment all the elements in the stack.
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
class CustomStack {
vector<pair<int, int>> st;
int msz;
public:
CustomStack(int maxSize): msz(maxSize) {
st.reserve(msz);
}

void push(int x) {
if(st.size() < msz) st.push_back({x, 0});
}

int pop() {
if(st.empty()) return -1;
int res = st.back().first + st.back().second;
if(st.size() != 1) {
st[st.size() - 2].second += st.back().second;
}
st.pop_back();

return res;
}

void increment(int k, int val) {
if(!st.empty()) {
st[min(k, (int) st.size()) - 1].second += val;
}
}
};

/**
* Your CustomStack object will be instantiated and called as such:
* CustomStack* obj = new CustomStack(maxSize);
* obj->push(x);
* int param_2 = obj->pop();
* obj->increment(k,val);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/12/10/PS/LeetCode/design-a-stack-with-increment-operation/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.