Skip to content

Commit eb0d5d2

Browse files
authored
Create 1381-design-a-stack-with-increment-operation.js
1 parent 780ccf0 commit eb0d5d2

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* @param {number} maxSize
3+
*/
4+
const CustomStack = function(maxSize) {
5+
this.stk = []
6+
this.size = maxSize
7+
this.inc = []
8+
};
9+
10+
/**
11+
* @param {number} x
12+
* @return {void}
13+
*/
14+
CustomStack.prototype.push = function(x) {
15+
if(this.stk.length === this.size) return
16+
this.stk.push(x)
17+
this.inc.push(0)
18+
};
19+
20+
/**
21+
* @return {number}
22+
*/
23+
CustomStack.prototype.pop = function() {
24+
if(this.stk.length === 0) return -1
25+
const e = this.stk.pop()
26+
const inc = this.inc.pop()
27+
if(this.inc.length) {
28+
this.inc[this.inc.length - 1] += inc
29+
}
30+
return e + inc
31+
};
32+
33+
/**
34+
* @param {number} k
35+
* @param {number} val
36+
* @return {void}
37+
*/
38+
CustomStack.prototype.increment = function(k, val) {
39+
const last = Math.min(k, this.inc.length) - 1
40+
if(last !== -1) {
41+
this.inc[last] += val
42+
}
43+
};
44+
45+
/**
46+
* Your CustomStack object will be instantiated and called as such:
47+
* var obj = new CustomStack(maxSize)
48+
* obj.push(x)
49+
* var param_2 = obj.pop()
50+
* obj.increment(k,val)
51+
*/

0 commit comments

Comments
 (0)