1
+ import java.util.*
2
+
3
+ /* *
4
+ * Your StockSpanner object will be instantiated and called as such:
5
+ * var obj = StockSpanner()
6
+ * var param_1 = obj.next(price)
7
+ */
8
+ class OnlineStockSpanKotlin901 {
9
+ // 100 80 60 70 60 75 85
10
+ // 1 1 1 2 1 4 6
11
+
12
+ // 100 1 add 100
13
+ // 100 1 -> 80 1 add 80
14
+ // 100 1 -> 80 1 -> 60 1 add 60
15
+ // 100 1 -> 80 1 -> 70 2 add 70
16
+ // 100 1 -> 80 1 -> 70 2 -> 60 1 add 60
17
+ // 100 1 -> 80 1 -> 75 4 add 75
18
+ // 100 1 -> 85 6 add 85
19
+
20
+ // 1384 ms
21
+ // first price, second count
22
+ private val priceCountStack: Stack <Pair <Int , Int >> = Stack ()
23
+ fun next (price : Int ): Int {
24
+ var count = 1
25
+ // stack peek won't remove the element, just return the reference of last added element
26
+ while (priceCountStack.isNotEmpty() && priceCountStack.peek().first <= price) {
27
+ count + = priceCountStack.pop().second
28
+ }
29
+ priceCountStack.push(Pair (price, count))
30
+ return count
31
+ }
32
+
33
+ /*
34
+ 1884 ms
35
+ private val prices: MutableList<Int> = ArrayList()
36
+ fun next(price: Int): Int {
37
+ var count = 1
38
+ loop@ for (index in prices.size - 1 downTo 0) {
39
+ when {
40
+ prices[index] <= price -> ++count
41
+ else -> break@loop
42
+ }
43
+ }
44
+ prices.add(price)
45
+ return count
46
+ }
47
+ */
48
+ }
49
+
50
+ fun main () {
51
+ val solution = OnlineStockSpanKotlin901 ()
52
+ // 1112146
53
+ print (solution.next(100 ))
54
+ print (solution.next(80 ))
55
+ print (solution.next(60 ))
56
+ print (solution.next(70 ))
57
+ print (solution.next(60 ))
58
+ print (solution.next(75 ))
59
+ print (solution.next(85 ))
60
+ }
0 commit comments