121. 买卖股票的最佳时机

54 阅读1分钟

题目链接:leetcode.cn/problems/be…

暴力解法

执行信息:

  • 时间复杂度:O(n^2)
  • 空间复杂度:O(1)
  • 循环次数:n(n - 1) / 2
function maxProfit(prices: number[]): number {
    let max = 0;
    for (let i = 0; i < prices.length - 1; i++) {
        for (let j = i + 1; j < prices.length; j++) {
            const profit = prices[j] - prices[i];
            if (profit > max) {
                max = profit;
            }
        }
    }

    return max;
};

一次遍历

调整思路,每天计算当前收益,一次遍历 执行信息:

  • 时间复杂度:O(n^2)
  • 空间复杂度:O(1)
function maxProfit(prices: number[]): number {
    let minPrice = Number.MAX_SAFE_INTEGER;
    let maxProfit = 0;
    for (let i = 0; i < prices.length; i++) {
        if (prices[i] < minPrice) {
            minPrice = prices[i];
        } else if (prices[i] - minPrice > maxProfit) {
            maxProfit = prices[i] - minPrice;
        }
    }

    return maxProfit;
};