121. Best Time to Buy and Sell Stock

Leetcode 问题: 121. Best Time to Buy and Sell Stock

题目

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

计算买卖股票的最大获益,买卖条件是 只能买卖 1 次

传入的阵列是所有天数的股票价格,例如 [7,1,5,3,6,4]

第几天 1 2 3 4 5 6
价格 7 1 5 3 6 4

Example

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.
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

答案

  1. 纪录前面天数最低价格当作买入价格
  2. 最低价格后面天数的股票价格比较,找出股票价格差最大的,就是最高获益

JavaScript

/**
 * @param {number[]} pricesList
 * @return {number}
 */
var maxProfit = function(pricesList) {
    if (pricesList.length == 0) {
        return 0;
    }
    // 目前最低价格
    let soFarMinPrice = pricesList[0];
    // 能够赚到最多的钱是多少
    let maxProfit = 0;

    for (let i = 1; i < pricesList.length; i++) {
        let currentPrice = pricesList[i];
        if (soFarMinPrice > currentPrice) {
            // 如果「目前最低价格」比「现在价格」高,将「现在价格」设定为「目前最低价格」
            soFarMinPrice = currentPrice;
        } else {
            // 「目前最低价格」比「现在价格」低,表示有获益
            // 目前获益 = 目前价格 - 目前最低价格
            let currentProfit = currentPrice - soFarMinPrice;
            // 计算出最大获益:之前的最大获益 vs 目前获益
            maxProfit = Math.max(maxProfit, currentProfit);
        }
    }

    return maxProfit;
};

参考资料