Skip to content

Instantly share code, notes, and snippets.

@Wendly
Created October 24, 2017 07:42
Show Gist options
  • Save Wendly/b843ce32d19cfcea56c4ed0fdfe144c6 to your computer and use it in GitHub Desktop.
Save Wendly/b843ce32d19cfcea56c4ed0fdfe144c6 to your computer and use it in GitHub Desktop.
Transactions Two
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;
}
}
@Wendly
Copy link
Author

Wendly commented Oct 24, 2017

class Solution {
    public int maxProfit(int[] prices) {
        if (prices.length == 0) return 0;
        return StreamUtils.zip(
            findMaxs(prices[0], Arrays.stream(prices)),
            findMaxs(prices[prices.length - 1], Arrays.stream(prices).inverse().map(x -> -x)).inverse(),
            (x, y) -> x + y
        ).max(Integer::max).get();
    }
    
    public IntStream findMaxs(int first, IntStream prices) {
        return prices.reduce(new int[2]{0, first}, (datas, x) -> {
            datas[0] = Math.max(datas[0], x - datas[1])
            datas[1] = Math.min(datas[1], x);
            return datas;
        });
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment