Created
March 1, 2015 18:37
-
-
Save dmnugent80/775caa0e56d594e64d5e to your computer and use it in GitHub Desktop.
Best Time to Buy and Sell Stock, max two transactions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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