在线股票跨度 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
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
1 1 1 2 1 4 6
广告