File tree 1 file changed +15
-16
lines changed 1 file changed +15
-16
lines changed Original file line number Diff line number Diff line change 1
1
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 ;
14
17
}
15
- stack .push (price );
16
- occurences .push (count );
17
- return count ;
18
- }
19
18
}
20
19
21
20
/**
You can’t perform that action at this time.
0 commit comments