Skip to content

Commit 42b7a31

Browse files
committed
buy and sell stock with maximum profit
1 parent 3379d2d commit 42b7a31

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/* problem statement
2+
first input is n representing the number of days
3+
after that we have n values ,representing the price of stock on that day
4+
ouput should be maximum profit , if you can buy and sell only one time
5+
*/
6+
7+
#include <iostream>
8+
using namespace std;
9+
int main()
10+
{
11+
int n;
12+
cin >> n; // it represent the number of days
13+
int arr[n]; // this array contains the prices of stock on that day
14+
for (int i = 0; i < n; i++)
15+
cin >> arr[i];
16+
int lsf = 9999999; //least so far
17+
int op = 0; //overall profit
18+
int pist = 0;
19+
for (int i = 0; i < n; i++)
20+
{
21+
if (arr[i] < lsf)
22+
{
23+
lsf = arr[i];
24+
}
25+
int pist = arr[i] - lsf; // if stock is sold today
26+
if (pist > op)
27+
{
28+
op = pist;
29+
}
30+
}
31+
cout << op << endl;
32+
}
33+
34+
/* sample input values are
35+
9
36+
11
37+
6
38+
7
39+
19
40+
4
41+
1
42+
6
43+
18
44+
4
45+
*/
46+
47+
/*sample output value for the upper input
48+
17
49+
*/

0 commit comments

Comments
 (0)