Skip to content

Commit d6ea23e

Browse files
authored
Update Online Stock Span.java
1 parent f72e69c commit d6ea23e

File tree

1 file changed

+15
-16
lines changed

1 file changed

+15
-16
lines changed

Medium/Online Stock Span.java

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,20 @@
11
class StockSpanner {
2-
Stack<Integer> stack;
3-
Stack<Integer> occurences;
4-
public StockSpanner() {
5-
stack = new Stack<>();
6-
occurences = new Stack<>();
7-
}
8-
9-
public int next(int price) {
10-
int count = 1;
11-
while (!stack.isEmpty() && stack.peek() <= price) {
12-
stack.pop();
13-
count += occurences.pop();
2+
3+
// Entry in stack is the current price and count of prices <= current price
4+
private final Stack<int[]> stack;
5+
6+
public StockSpanner() {
7+
this.stack = new Stack<>();
8+
}
9+
10+
public int next(int price) {
11+
int count = 1;
12+
while (!stack.isEmpty() && stack.peek()[0] <= price) {
13+
count += stack.pop()[1];
14+
}
15+
stack.push(new int[]{price, count});
16+
return count;
1417
}
15-
stack.push(price);
16-
occurences.push(count);
17-
return count;
18-
}
1918
}
2019

2120
/**

0 commit comments

Comments
 (0)