-
Notifications
You must be signed in to change notification settings - Fork 0
/
buySellStock.cpp
58 lines (46 loc) · 1.27 KB
/
buySellStock.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// C++ Program to find best buying and selling days
#include <bits/stdc++.h>
using namespace std;
// This function finds the buy sell
// schedule for maximum profit
void stockBuySell(int price[], int n)
{
// Prices must be given for at least two days
if (n == 1)
return;
// Traverse through given price array
int i = 0;
while (i < n - 1) {
// Find Local Minima
// Note that the limit is (n-2) as we are
// comparing present element to the next element
while ((i < n - 1) && (price[i + 1] <= price[i]))
i++;
// If we reached the end, break
// as no further solution possible
if (i == n - 1)
break;
// Store the index of minima
int buy = i++;
// Find Local Maxima
// Note that the limit is (n-1) as we are
// comparing to previous element
while ((i < n) && (price[i] >= price[i - 1]))
i++;
// Store the index of maxima
int sell = i - 1;
cout << "\nBuy on day: " << buy
<< "\t Sell on day: " << sell << endl;
}
}
// Driver code
int main()
{
// Stock prices on consecutive days
int price[] = { 2,3,4,2,1,2,3,2,4 };
int n = sizeof(price) / sizeof(price[0]);
// Fucntion call
stockBuySell(price, n);
return 0;
}
// This is code is contributed by rathbhupendra