File tree Expand file tree Collapse file tree 1 file changed +11
-21
lines changed Expand file tree Collapse file tree 1 file changed +11
-21
lines changed Original file line number Diff line number Diff line change 1
1
class StockSpanner {
2
- stack <pair <int ,int >> s ; //1st is index and 2nd is value
3
- int index ;
4
- public :
5
- StockSpanner () {
6
- ios ::sync_with_stdio (false );
7
- cin .tie (0 );
8
- index = -1 ;
2
+ Stack <int []> st ;
3
+ public StockSpanner () {
4
+ st = new Stack <>();
9
5
}
10
-
11
- int next (int price ) {
12
- index +=1 ;
13
-
14
- while (!s .empty () && s .top ().second <=price ) //Find the previous greater element
15
- s .pop ();
16
- //If there is no previous greater element
17
- if (s .empty ())
18
- { s .push ({index ,price }); return index +1 ; }
19
-
20
- int result = s .top ().first ;
21
- s .push ({index ,price });
22
- return index -result ;
6
+ public int next (int price ) {
7
+ int span = 1 ;
8
+ while (!st .isEmpty () && st .peek ()[0 ] <= price ) {
9
+ span += st .pop ()[1 ];
10
+ }
11
+ st .push (new int [] {price , span });
12
+ return span ;
23
13
}
24
- };
14
+ }
You can’t perform that action at this time.
0 commit comments