Skip to content

Commit d0461f7

Browse files
authored
Create StockBuyAAndSell.cpp
1 parent d687bab commit d0461f7

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

C++/StockBuyAAndSell.cpp

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// C++ implementation of the approach
2+
#include <bits/stdc++.h>
3+
using namespace std;
4+
5+
// Function to return the maximum profit
6+
// that can be made after buying and
7+
// selling the given stocks
8+
int maxProfit(int price[], int start, int end)
9+
{
10+
11+
// If the stocks can't be bought
12+
if (end <= start)
13+
return 0;
14+
15+
// Initialise the profit
16+
int profit = 0;
17+
18+
// The day at which the stock
19+
// must be bought
20+
for (int i = start; i < end; i++) {
21+
22+
// The day at which the
23+
// stock must be sold
24+
for (int j = i + 1; j <= end; j++) {
25+
26+
// If buying the stock at ith day and
27+
// selling it at jth day is profitable
28+
if (price[j] > price[i]) {
29+
30+
// Update the current profit
31+
int curr_profit
32+
= price[j] - price[i]
33+
+ maxProfit(price, start, i - 1)
34+
+ maxProfit(price, j + 1, end);
35+
36+
// Update the maximum profit so far
37+
profit = max(profit, curr_profit);
38+
}
39+
}
40+
}
41+
return profit;
42+
}
43+
44+
// Driver code
45+
int main()
46+
{
47+
int price[] = { 100, 180, 260, 310, 40, 535, 695 };
48+
int n = sizeof(price) / sizeof(price[0]);
49+
50+
cout << maxProfit(price, 0, n - 1);
51+
52+
return 0;
53+
}

0 commit comments

Comments
 (0)