-
Notifications
You must be signed in to change notification settings - Fork 0
/
OnlineStockSpan.java
45 lines (42 loc) · 1.17 KB
/
OnlineStockSpan.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// https://leetcode.com/problems/online-stock-span/
// #stack
class StockSpanner {
/* User array to store consecutive days at i-th => LOOP TO CHECK
[100, 65, 60, 70, 60, 75, 85],
1. 1. 1. 3. 1. 5 6
*/
/*
optimize: use stack instead of list, and only store the greater item than current.
65 60 70 60 => not need anymore after current 75
*/
private ArrayList<Integer> stockSpanList;
private ArrayList<Integer> stockPriceList;
public StockSpanner() {
stockSpanList = new ArrayList<>();
stockPriceList = new ArrayList<>();
}
public int next(int price) {
if (stockPriceList.isEmpty()) {
stockPriceList.add(price);
stockSpanList.add(1);
return 1;
}
int idx = stockPriceList.size() - 1;
int ret = 1;
while (idx >= 0) {
if (stockPriceList.get(idx) <= price) {
ret += stockSpanList.get(idx);
idx -= stockSpanList.get(idx);
} else {
break;
}
}
stockPriceList.add(price);
stockSpanList.add(ret);
return ret;
}
}
/**
* Your StockSpanner object will be instantiated and called as such: StockSpanner obj = new
* StockSpanner(); int param_1 = obj.next(price);
*/