Skip to content

Commit 46ea5b9

Browse files
authored
added array solution for 1381 with test cases (fishercoder1534#127)
1 parent c25b0fb commit 46ea5b9

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

src/main/java/com/fishercoder/solutions/_1381.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,4 +79,43 @@ public void increment(int k, int val) {
7979
}
8080
}
8181
}
82+
83+
/**
84+
* Implementation of Stack using Array
85+
*/
86+
public static class Solution2{
87+
public static class CustomStack {
88+
private int top;
89+
private int maxSize;
90+
private int stack[];
91+
public CustomStack(int maxSize) {
92+
this.maxSize = maxSize;
93+
this.stack = new int[maxSize];
94+
}
95+
96+
public void push(int x) {
97+
if(top == maxSize) return;
98+
stack[top] = x;
99+
top++;
100+
}
101+
102+
public int pop() {
103+
if(top == 0)
104+
return -1;
105+
int popValue = stack[top-1];
106+
stack[top-1] = 0;
107+
top--;
108+
return popValue;
109+
}
110+
111+
public void increment(int k, int val) {
112+
if(top == 0 || k == 0) return;
113+
for(int i = 0; i<k; i++){
114+
if(i == top)
115+
break;
116+
stack[i] += val;
117+
}
118+
}
119+
}
120+
}
82121
}

src/test/java/com/fishercoder/_1381Test.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
public class _1381Test {
99
private static _1381.Solution1.CustomStack customStack;
10+
private static _1381.Solution2.CustomStack customStack2;
1011

1112
@Test
1213
public void test1() {
@@ -24,5 +25,20 @@ public void test1() {
2425
assertEquals(201, customStack.pop());
2526
assertEquals(-1, customStack.pop());
2627
}
28+
@Test
29+
public void test2() {
30+
customStack2 = new _1381.Solution2.CustomStack(3);
31+
customStack2.push(-1);
32+
customStack2.push(20);
33+
assertEquals(20, customStack2.pop());
34+
customStack2.push(30);
35+
customStack2.push(40);
36+
customStack2.push(50);
37+
customStack2.increment(5, 100);
38+
assertEquals(140, customStack2.pop());
39+
assertEquals(130, customStack2.pop());
40+
assertEquals(99, customStack2.pop());
41+
42+
}
2743

2844
}

0 commit comments

Comments
 (0)