Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions Dynamic Programming/Best Time to Buy and Sell Stock III
Original file line number Diff line number Diff line change
@@ -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;
}
}