123. Best Time to Buy and Sell Stock III

Description

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Constraints

  • 1 <= prices.length <= 105

  • 0 <= prices[i] <= 10

Approach

Examples

Input: prices = [1,2,3,4,5]

Output: 4

Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.

Solutions

/**
 * Time complexity : O(N) where N is the length of the input sequence, 
 *    since we have two iterations of length N.
 * Space complexity : O(N) for the two arrays that we keep in the algorithm.
 */

class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length <= 1) return 0;
        int n = prices.length;
        
        int[] leftProfits = new int[n];
        int[] rightProfits = new int[n+1];
        
        int leftMin = Integer.MAX_VALUE;
        int rightMax = Integer.MIN_VALUE;
        
        for(int l = 0; l < n; l++) {
            leftMin = Math.min(leftMin, prices[l]);
            leftProfits[l] = Math.max(leftProfits[l], prices[l]-leftMin);
            
            int r = n-1-l;
            rightMax = Math.max(rightMax, prices[r]);
            rightProfits[r] = Math.max(rightProfits[r+1], rightMax-prices[r]);
        }
        
        int maxProfit = 0;
        for(int i = 0; i < n; i++) {
            maxProfit = Math.max(maxProfit, leftProfits[i]+rightProfits[i]);
        }
        
        return maxProfit;
    }
}

Follow up

Last updated

Was this helpful?