線上股票跨度 C++
假設我們有一個 API,它會收集一些股票每日價格報價,並返回該股票當前日的跨度。此處的股票跨度定義為以下內容 −
- 自今日開始往前(包括今日)連續天數內,該股票價格低於或等於當日價格的最大值。
例如,如果我們檢視 7 天股票份額記錄,如 [100, 80, 60, 70, 60, 75, 85],則股票跨度應為 [1, 1, 1, 2, 1, 4, 6]。當呼叫此模組時,我們必須編寫該 API 的實際模組
為了解決這個問題,我們將遵循以下步驟 −
- 定義兩個陣列 st、v 和計數器,將計數器設定為 0
- 將計數器加 1
- 當 st 不為空且價格 >= v[棧頂元素] 時
- 從棧中彈出。
- 當棧為空時,答案 := 計數器,否則答案 := 計數器 – 棧頂
- 在 v 中插入價格
- 在 st 中插入計數器
- 返回答案
讓我們研究以下實現以更好地理解 −
示例
#include <bits/stdc++.h> using namespace std; class StockSpanner { public: vector <int> st; int counter; vector <int> v; StockSpanner() { counter = 0; } int next(int price) { counter++; while(!st.empty() && price >= v[st.back() - 1])st.pop_back(); int ans = st.empty() ? counter : counter - st.back(); v.push_back(price); st.push_back(counter); return ans ; } }; main(){ StockSpanner ob; cout <<(ob.next(100)) << endl; cout <<(ob.next(80)) << endl; cout <<(ob.next(60)) << endl; cout <<(ob.next(70)) << endl; cout <<(ob.next(60)) << endl; cout <<(ob.next(75)) << endl; cout <<(ob.next(85)) << endl; }
輸入
Initialize the class, then call next() method using different values. See the main() method
輸出
1 1 1 2 1 4 6
廣告