- Today
- Total
작심삼일
[LeetCode] 901 | Online Stock Span | Python 본문
문제 링크: https://leetcode.com/problems/online-stock-span/
문제
Design an algorithm that collects daily price quotes for some stock and returns the span of that stock's price for the current day.
The span of the stock's price today is defined as the maximum number of consecutive days (starting from today and going backward) for which the stock price was less than or equal to today's price.
- For example, if the price of a stock over the next 7 days were [100,80,60,70,60,75,85], then the stock spans would be [1,1,1,2,1,4,6].
Implement the StockSpanner class:
- StockSpanner() Initializes the object of the class.
- int next(int price) Returns the span of the stock's price given that today's price is price.
조건
- 1 <= price <= $10^5$
- At most 104 calls will be made to next.
내 풀이
Monotone Queue, 단조증가 혹은 단조감소하는 큐를 사용한다.
Monotone Queue(stack)에 현재 price를 넣을 때는, 현재 price보다 작은 값은 모두 pop한 뒤에 추가하기 때문에 현재 price보다 큰 값들이 내림차순으로 정렬되어 있다. (ex. self.stack = [[a, 1], [b, 1], [c, 2]], a > b > c > price)
self.stack에는 [price, 위치]를 저장한다.
이때의 위치는 내가 몇개의 수를 포함하고있는 지를 뜻한다.
위의 예시(ex. self.stack = [[a, 1], [b, 1], [c, 2]])를 보면, [c, 2]이기 때문에, b와 c 사이에 b > c > d를 만족하는 d가 포함되어있음을 알 수 있다.
코드
class StockSpanner:
def __init__(self):
self.stack = []
def next(self, price: int) -> int:
res = 1
while self.stack and self.stack[-1][0] <= price:
res += self.stack.pop()[1]
self.stack.append([price, res])
return res
# Your StockSpanner object will be instantiated and called as such:
# obj = StockSpanner()
# param_1 = obj.next(price)
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 947 | Most Stones Removed with Same Row or Column | Python (0) | 2022.11.14 |
---|---|
[LeetCode] 1047 | Remove All Adjacent Duplicates In String | Python (0) | 2022.11.10 |
[LeetCode] 1544 | Make The String Great | Python (0) | 2022.11.09 |
[LeetCode] 1323 | Maximum 69 Number | Python (0) | 2022.11.07 |
[LeetCode] 2131 | Longest Palindrome by Concatenating Two Letter Words | Python (0) | 2022.11.03 |