-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathsolution.cpp
47 lines (43 loc) · 981 Bytes
/
solution.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
class CustomStack
{
public:
int maxSize;
vector<int> stack;
vector<int> inc;
CustomStack(int maxSize)
{
this->maxSize = maxSize;
}
void push(int x)
{
if (stack.size() < maxSize)
{
stack.push_back(x);
inc.push_back(0); // Initialize increment for this element
}
}
int pop()
{
if (stack.empty())
{
return -1;
}
int idx = stack.size() - 1;
int result = stack[idx] + inc[idx]; // Apply any pending increments
if (idx > 0)
{
inc[idx - 1] += inc[idx]; // Propagate increment to the next element
}
stack.pop_back();
inc.pop_back();
return result;
}
void increment(int k, int val)
{
int limit = min(k, (int)stack.size()) - 1;
if (limit >= 0)
{
inc[limit] += val; // Add increment to the bottom k-th element
}
}
};