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.


Find max diff values in an array, O(n)

public int maxProfit(int[] prices) {
    if(prices.length < 2) {
        return 0;
    }
    int maxProfit = 0, min = prices[0];
    for(int i = 1; i < prices.length; i++){
        if(prices[i] >= min)
            maxProfit = Math.max(maxProfit, prices[i] - min);
        else min = prices[i];
    }
    return maxProfit;
}

results matching ""

    No results matching ""