2. Best Time to Buy and Sell Stock

Best Time to Buy and Sell Stock - LeetCode

Time: O(n^2): TLE

Space: O(1)

var maxProfit = function (prices) {

    // TLE
    let profit = 0;
    for (let i = 0; i < prices.length; i++) {
        const buyPrice = prices[i];
        for (let j = i + 1; j < prices.length; j++) {
            const sellPrice = prices[j];
            const diff = sellPrice - buyPrice;
            profit = Math.max(diff, profit);
        }
    }
    
    return profit;
};

Time: O(n)

Space: O(n)

Two pointer: best

Time: O(n)

Space: O(1)

Last updated