[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.
Note: There may be multiple possible solutions. Return any one of them. Any correct solution will result in an output of 1, whereas wrong solutions will result in an output of 0.

  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution{
public:
//Function to find the days of buying and selling stock for max profit.
vector<vector<int>> stockBuySell(vector<int> A, int n){
vector<vector<int>> res;
for(int i = 0; i < n - 1; i++) {
if(A[i] >= A[i + 1]) continue;
if(res.empty() or res.back()[1] != i) res.push_back({i, i + 1});
else res.back()[1] = i + 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/22/PS/GeeksforGeeks/stock-buy-and-sell-2/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.