From b5df9d1d10cd29e7e581a9a4e2a2bbde0305130e Mon Sep 17 00:00:00 2001 From: rtvksingh <56456010+rtvksingh@users.noreply.github.com> Date: Fri, 1 Oct 2021 11:45:29 +0530 Subject: [PATCH] Best Time to Buy and Sell Stock III --- .../Best Time to Buy and Sell Stock III | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Dynamic Programming/Best Time to Buy and Sell Stock III diff --git a/Dynamic Programming/Best Time to Buy and Sell Stock III b/Dynamic Programming/Best Time to Buy and Sell Stock III new file mode 100644 index 0000000..3505ecd --- /dev/null +++ b/Dynamic Programming/Best Time to Buy and Sell Stock III @@ -0,0 +1,15 @@ +class Solution { + public int maxProfit(int[] prices) { + int maxProfit1=0; + int maxProfit2=0; + int lowestBuyPrice1=Integer.MAX_VALUE; + int lowestBuyPrice2=Integer.MAX_VALUE; + for(int val:prices){ + maxProfit2=Math.max(maxProfit2,val-lowestBuyPrice2); + lowestBuyPrice2=Math.min(lowestBuyPrice2,val-maxProfit1); + maxProfit1=Math.max(maxProfit1,val-lowestBuyPrice1); + lowestBuyPrice1=Math.min(lowestBuyPrice1,val); + } + return maxProfit2; + } +}