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; + } +}