From a221db8b47580730e5557dfe3d49ffb0fe466397 Mon Sep 17 00:00:00 2001 From: Eatswap Date: Fri, 21 Oct 2022 13:28:22 +0800 Subject: [PATCH] add: 221021-CN --- cpp/2210/221021-CN.cpp | 43 +++++++++++++++++++++++++++++++++++++++++ cpp/2210/CMakeLists.txt | 2 +- 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 cpp/2210/221021-CN.cpp diff --git a/cpp/2210/221021-CN.cpp b/cpp/2210/221021-CN.cpp new file mode 100644 index 0000000..a9004f8 --- /dev/null +++ b/cpp/2210/221021-CN.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +/** + * 901. 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. + */ + +class StockSpanner { +private: + std::stack> s; + int pos = 0; + +public: + StockSpanner() = default; + + int next(int price) { + while (!s.empty() && s.top().first <= price) + s.pop(); + int ret = pos - (s.empty() ? -1 : s.top().second); + s.push({price, pos++}); + return ret; + } +}; + +int main() { + StockSpanner s; + std::cout << s.next(100) << "\n"; + std::cout << s.next(80) << "\n"; + std::cout << s.next(60) << "\n"; + std::cout << s.next(70) << "\n"; + std::cout << s.next(60) << "\n"; + std::cout << s.next(75) << "\n"; + std::cout << s.next(85) << "\n"; + return 0; +} diff --git a/cpp/2210/CMakeLists.txt b/cpp/2210/CMakeLists.txt index b8cde8e..9231094 100644 --- a/cpp/2210/CMakeLists.txt +++ b/cpp/2210/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2210) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2210 221020.cpp) +ADD_EXECUTABLE(2210 221021-CN.cpp)