Skip to content

Commit 12b6a17

Browse files
authored
Create leetcode-901.cpp
1 parent 22e2683 commit 12b6a17

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

Stack/leetcode-901.cpp

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/*
2+
// https://leetcode.com/problems/online-stock-span/description/?envType=study-plan-v2&envId=leetcode-75
3+
4+
901. Online Stock Span
5+
Solved
6+
Medium
7+
8+
Topics
9+
Companies
10+
Design an algorithm that collects daily price quotes for some stock and returns the span of that stock's price for the current day.
11+
12+
The span of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day.
13+
14+
For example, if the prices of the stock in the last four days is [7,2,1,2] and the price of the stock today is 2, then the span of today is 4 because starting from today, the price of the stock was less than or equal 2 for 4 consecutive days.
15+
Also, if the prices of the stock in the last four days is [7,34,1,2] and the price of the stock today is 8, then the span of today is 3 because starting from today, the price of the stock was less than or equal 8 for 3 consecutive days.
16+
Implement the StockSpanner class:
17+
18+
StockSpanner() Initializes the object of the class.
19+
int next(int price) Returns the span of the stock's price given that today's price is price.
20+
21+
22+
Example 1:
23+
24+
Input
25+
["StockSpanner", "next", "next", "next", "next", "next", "next", "next"]
26+
[[], [100], [80], [60], [70], [60], [75], [85]]
27+
Output
28+
[null, 1, 1, 1, 2, 1, 4, 6]
29+
30+
Explanation
31+
StockSpanner stockSpanner = new StockSpanner();
32+
stockSpanner.next(100); // return 1
33+
stockSpanner.next(80); // return 1
34+
stockSpanner.next(60); // return 1
35+
stockSpanner.next(70); // return 2
36+
stockSpanner.next(60); // return 1
37+
stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.
38+
stockSpanner.next(85); // return 6
39+
40+
41+
Constraints:
42+
43+
1 <= price <= 105
44+
At most 104 calls will be made to next.
45+
*/
46+
47+
class StockSpanner {
48+
stack <pair<int, int>> dp; // maintails decreasing
49+
int i;
50+
public:
51+
StockSpanner() {
52+
dp = stack <pair<int, int>>();
53+
}
54+
55+
int next(int price) {
56+
int days = 1;
57+
while (!dp.empty() && dp.top().first <=price) {
58+
days += dp.top().second;
59+
dp.pop();
60+
}
61+
dp.push({price, days});
62+
return days;
63+
}
64+
};

0 commit comments

Comments
 (0)