LeetCode #121 - Best Time to Buy and Sell Stock (JavaScript)

const maxProfit = (prices) => {
    if (prices.length < 2) {
        return 0;
    }

    /*
     * It was hard for me to make up my mind here,
     * but here's explanation, let's take:
     *  [2,7,1,3]
     *
     * The trick is that we are tracking both min and profit at the same time.
     *
     * `min` will be changing every time we've found lesser value
     * `profit` will change only if we've found something more profitable while walking array
     */
    
    let min = prices[0];
    let profit = 0;
    
    for (let i = 1; i < prices.length; i++) {
        min = Math.min(prices[i], min);
        profit = Math.max(profit, prices[i] - min);
    }
    
    return profit;
}