Skip to content

Commit cfdfe3f

Browse files
solved on 21/10/23
1 parent dbbe50a commit cfdfe3f

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

LC_59_BuyAndSellStocks.cpp

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
void maxProfitFinder(vector<int> &prices, int i, int &minPrice, int &maxProfit){
5+
// base
6+
if (i == prices.size())
7+
{
8+
return;
9+
}
10+
11+
// sol for one case
12+
if (prices[i] < minPrice) minPrice = prices[i]; // update minPrice if current price is less than minPrice
13+
int todaysProfit = prices[i] - minPrice; // calculate profit for today
14+
if (todaysProfit > maxProfit) maxProfit = todaysProfit; // update maxProfit if today's profit is greater than maxProfit
15+
16+
// recursive call
17+
maxProfitFinder(prices, i + 1, minPrice, maxProfit); // call for next day
18+
}
19+
20+
int maxProfit(vector<int> &prices)
21+
{
22+
// TLE - tc: O(n^2), sc: O(1)
23+
// int diff = 0;
24+
// for (int i = 0; i < prices.size(); i++)
25+
// {
26+
// for (int j = i + 1; j < prices.size(); j++)
27+
// {
28+
// diff = max(prices[j] - prices[i], diff);
29+
// }
30+
// }
31+
// return diff;
32+
33+
// recursive - tc: O(n), sc: O(n)
34+
int minPrice = INT_MAX;
35+
int maxProfit = INT_MIN;
36+
maxProfitFinder(prices, 0, minPrice, maxProfit);
37+
return maxProfit;
38+
}
39+
40+
int main()
41+
{
42+
vector<int> v = {7,1,5,3,6,4};
43+
cout << maxProfit(v);
44+
return 0;
45+
}

0 commit comments

Comments
 (0)