diff --git a/Arrays/Buy And Sell Stocks 3.cpp b/Arrays/Buy And Sell Stocks 3.cpp new file mode 100644 index 0000000..49097bf --- /dev/null +++ b/Arrays/Buy And Sell Stocks 3.cpp @@ -0,0 +1,29 @@ +int maxProfit(vector& prices) { + int n = prices.size(); + if(n <= 1) + return 0; + if(n == 2) { + return max((prices[1] - prices[0]), 0); + } + + vector secondMax(n,0); + + int maxPrice = prices[n-1]; + int maxProfit = 0; + for(int i=n-2;i>=0;i--) { + maxProfit = max(maxProfit, maxPrice - prices[i]); + secondMax[i] = maxProfit; + maxPrice = max(maxPrice, prices[i]); + } + + int minPrice = prices[0]; + int ans = 0; + for(int i=1;i