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;
};

參考資料