Created
October 24, 2017 07:42
-
-
Save Wendly/b843ce32d19cfcea56c4ed0fdfe144c6 to your computer and use it in GitHub Desktop.
Transactions Two
This file contains 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
class Solution { | |
public int maxProfit(int[] prices) { | |
if (prices.length == 0) return 0; | |
int[] left = findMaxs(prices); | |
int[] right = findMaxs(IntStream.rangeClosed(1, prices.length) | |
.map(i -> -prices[prices.length - i]).toArray()); | |
int max = 0; | |
for (int i = 1; i < prices.length; i++) { | |
max = Math.max(max, left[i] + right[prices.length - i - 1]); | |
} | |
return max; | |
} | |
public int[] findMaxs(int[] prices) { | |
int[] maxs = new int[prices.length]; | |
int min = prices[0]; | |
maxs[0] = 0; | |
for (int i = 1; i < prices.length; i++) { | |
maxs[i] = Math.max(maxs[i - 1], prices[i] - min); | |
min = Math.min(min, prices[i]); | |
} | |
return maxs; | |
} | |
} |
Author
Wendly
commented
Oct 24, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment