share my java solution


  • 0
    W
    public int maxProfit(int[] prices) {
        int res = 0;
        int len = prices.length;
        if(len < 2) return 0;
        int[] leftmax = new int[len];
        int[] rightmax = new int[len];
        leftmax[0] = 0;
        rightmax[len-1] = 0;
        int left = prices[0];
        int right = prices[len-1];
        for(int i = 1; i < len; i++) {
            left = Math.min(left, prices[i]);
            leftmax[i] = Math.max(leftmax[i-1], prices[i] - left);
            right = Math.max(right, prices[len-1-i]);
            rightmax[len-1-i] = Math.max(rightmax[len-i], right - prices[len-1-i]);
        }
        for(int i = 0; i < len; i++) {
            res = Math.max(res, leftmax[i] + rightmax[i]);
        }
        return res;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.