LeetCode 剑指Offer 63. 股票的最大利润

题目链接:https://leetcode-cn.com/problems/gu-piao-de-zui-da-li-run-lcof/

使用一个变量维护数组中的最小元素,然后每次拿当前保存的res和在当天卖出所获得的利润作比较,取较大值。

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
            let minIndex = 0;
	    let res = 0;
            let min = prices[0];
            for (let i = 1; i < prices.length; i++) {
	        res = Math.max(res, prices[i] - min);
		    if (prices[i] < min) {
		        min = prices[i];
		    }
	    }
            return res;
};

O(n)的时间复杂度和O(1)的空间复杂度

猜你喜欢

转载自blog.csdn.net/ySFRaabbcc/article/details/108805721