MrainW's Home

All things come to those who wait!

0%

LeetCode 1381. Design a Stack With Increment Operation

Question

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.

https://leetcode.com/problems/design-a-stack-with-increment-operation/

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
class CustomStack {
int n;
int[] inc;
Stack<Integer> stack = new Stack<>();
public CustomStack(int maxSize) {
n = maxSize;
inc = new int[n];
}

public void push(int x) {
if(stack.size()<n) stack.push(x);
}

public int pop() {
int i = stack.size()-1;
if(i<0) return -1;
if(i>0) inc[i-1] += inc[i];
int res = stack.pop() + inc[i];
inc[i] = 0;
return res;
}

public void increment(int k, int val) {
int i = Math.min(k, stack.size()) - 1;
if(i >= 0) inc[i] += val;
}
}

Welcome to my other publishing channels