Design a Stack With Increment Operation LeetCode solution in Java

1
class CustomStack {
2

3
int[] stack;
4
int top;
5

6
public CustomStack(int maxSize) {
7

8
// intialise the stack and the top
9
stack = new int[maxSize];
10
top = -1;
11
}
12

13
public void push(int x) {
14

15
// if the stack is full just skip
16
if (top == stack.length - 1) return;
17

18
// add to the stack
19
top++;
20
stack[top] = x;
21
}
22

23
public int pop() {
24

25
// if stack is empty return -1
26
if (top == -1) return -1;
27

28
// remove/pop the top element
29
top--;
30
return stack[top + 1];
31
}
32

33
public void increment(int k, int val) {
34

35
// got to increment the min of the elements present in the stack and k
36
int n = Math.min(top + 1, k);
37

38
for (int i = 0; i < n; i++) {
39
stack[i] += val;
40
}
41
}
42
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0