Skip to content

Commit dd39b08

Browse files
committed
added Buy & Sell stock 3
1 parent 93c3f1d commit dd39b08

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Arrays/Buy And Sell Stocks 3.cpp

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
int maxProfit(vector<int>& prices) {
2+
int n = prices.size();
3+
if(n <= 1)
4+
return 0;
5+
if(n == 2) {
6+
return max((prices[1] - prices[0]), 0);
7+
}
8+
9+
vector<int> secondMax(n,0);
10+
11+
int maxPrice = prices[n-1];
12+
int maxProfit = 0;
13+
for(int i=n-2;i>=0;i--) {
14+
maxProfit = max(maxProfit, maxPrice - prices[i]);
15+
secondMax[i] = maxProfit;
16+
maxPrice = max(maxPrice, prices[i]);
17+
}
18+
19+
int minPrice = prices[0];
20+
int ans = 0;
21+
for(int i=1;i<n;i++) {
22+
int currentProfit = prices[i] - minPrice;
23+
minPrice = min(minPrice, prices[i]);
24+
ans = max(ans,currentProfit);
25+
if(i != n-1)
26+
ans = max(ans, currentProfit + secondMax[i+1]);
27+
}
28+
return ans;
29+
}

0 commit comments

Comments
 (0)