int maxProfit (int[] prices) {
        if (prices.length < 2) return 0;
        int[] f = new int[prices.length], g = new int[prices.length];

        for (int i = 1, bottom = prices[0]; i < prices.length; i++) {
            if (prices[i] < bottom) bottom = prices[i];
            f[i] = (f[i - 1] > prices[i] - bottom) ? f[i - 1] : prices[i] - bottom;
        }
        for (int i = prices.length - 2, peak = prices[prices.length - 1]; i >= 0; i--) {
            if (prices[i] > peak) peak = prices[i];
            g[i] = (g[i + 1] > peak - prices[i]) ? g[i + 1] : peak - prices[i];
        }

        int profit = 0;
        for (int i = 0; i < prices.length; i++) {
            if (f[i] + g[i] > profit) profit = f[i] + g[i];
        }

        return profit;
    }