Best Time to Buy and Sell Stock

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

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Ideas:

Only one transaction, so find the max difference

Code:

public int maxProfit(int[] prices) {
    if (prices == null || prices.length <= 1) return 0;

    int min = Integer.MAX_VALUE;
    int max = 0;
    for (int i : prices) {
        if (i < min) {
            min = i;
        }

        if (i-min > max) {
            max = i-min;
        }
    }

    return max;
}

results matching ""

    No results matching ""