最佳买卖股票时间

给你一个数组 pricesprices[i] 是第 i 天股票的价格。

你要通过选一天去买入一只股票然后在未来的另一天卖出以获得最大的收益。

返回你能从这次交易中获得的最大收益。如果你不能盈利,则返回 0

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

约束:

  • 1 <= prices.length <= 10 5
  • 0 <= prices[i] <= 104

解法

从题意和例子可以看出,买卖只能操作一次,相当于求在后面元素的值比前面元素大的条件下,求数组中两个元素的最大差值。

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    let min = 0; // 历史最低买入价(不含当天)
    let max = 0; // 历史最高利润(含当天)
    
    for (let i = 0; i < prices.length; i++) {
        if (i === 0) {
            min = prices[i];
            continue;
        }
        
        min = Math.min(min, prices[i - 1]);
        const todayMax = prices[i] - min;
        
        max = Math.max(max, todayMax);
    }
    
    return max;
};