Best Time to Buy and Sell Stock

Given 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:
A transaction is a buy & a sell. You may not engage in multiple transactions at the same time (you must sell the stock before you buy again).

Example :
Input:   price[] = {10, 22, 5, 75, 65, 80}
Output:  87
Buy at price 10, sell at 22, buy at 5 and sell at 80

Discussion


public int maxProfit(int[] priceList) {
    int len = priceList.length;
    if (priceList == null || len < 2) return 0;

    int[] left = new int[len];
    int[] right = new int[len];

    left[0] = 0; 
    int min = priceList[0];
    for (int i = 1; i < len; i++) {
        min = Math.min(min, priceList[i]);
        left[i] = Math.max(left[i - 1], priceList[i] - min);
    }

    right[len - 1] = 0;
    int max = priceList[len - 1];
    for (int i = len - 2; i >= 0; i--) {
        max = Math.max(max, priceList[i]);
        right[i] = Math.max(right[i + 1], max - priceList[i]);
    }

    int profit = 0;
    for (int i = 0; i < len; i++) {
        profit = Math.max(profit, left[i] + right[i]);
    }

    return profit;
}

Comments

Popular posts from this blog

Longest Subarray with Sum greater than Equal to K

Search in Rotated Sorted Array

Consistent Hashing