Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Created March 1, 2015 18:37
Show Gist options
  • Select an option

  • Save dmnugent80/775caa0e56d594e64d5e to your computer and use it in GitHub Desktop.

Select an option

Save dmnugent80/775caa0e56d594e64d5e to your computer and use it in GitHub Desktop.
Best Time to Buy and Sell Stock, max two transactions
public class Solution {
public int maxProfit(int[] prices) {
if (prices.length == 0) return 0;
int[] rearProfits = new int[prices.length];
int maxPrice = prices[prices.length-1];
int maxProfit = 0;
int price = 0;
for (int i = prices.length-2; i >= 0; i--){
price = prices[i];
maxPrice = Math.max(price, maxPrice);
maxProfit = Math.max(maxPrice - price, maxProfit);
rearProfits[i] = maxProfit;
}
int finalMax = rearProfits[0];
int minPrice = prices[0];
maxProfit = 0;
for (int i = 1; i < prices.length-1; i++){
price = prices[i];
minPrice = Math.min(minPrice, price);
maxProfit = Math.max(maxProfit, price - minPrice);
finalMax = Math.max(finalMax, maxProfit + rearProfits[i+1]);
}
return finalMax;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment