[Geeks for Geeks] Stock buy and sell

Stock buy and sell

The cost of stock on each day is given in an array A[] of size N. Find all the days on which you buy and sell the stock so that in between those days your profit is maximum.

  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void stockBuySell(int A[], int n) {
vector<pair<int,int>> st;
for(int i = 0; i < n - 1; i++) {
if(A[i] < A[i + 1]) {
if(st.empty() or st.back().second != i) st.push_back({i, i + 1});
else st.back().second = i + 1;
}
}
if(st.empty()) cout<<"No Profit";

for(auto& p : st) {
cout<<"("<<p.first<<' '<<p.second<<") ";
}
cout<<endl;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/21/PS/GeeksforGeeks/stock-buy-and-sell/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.