122. Best Time to Buy and Sell Stock II

Leetcode 問題: 122. Best Time to Buy and Sell Stock II

題目

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.

計算買賣股票的最大獲益,買賣條件是 可以買賣多次

傳入的陣列是所有天數的股票價格,例如 [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: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.
Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Total profit is 4.

答案

所有上漲的獲益的總和,就是最大可獲益的數字

JavaScript

/**
 * @param {number[]} pricesList
 * @return {number}
 */
var maxProfit = function(pricesList) {
    let maxProfit = 0;

    for (let i = 1; i < pricesList.length; i++) {
        // 先前價格
        let previousPrice = pricesList[i-1];
        // 現在價格
        let currentPrice = pricesList[i];

        if (currentPrice > previousPrice) {
            // 如果「現在價格」大於「先前價格」,表示有獲益,將這次獲益加入
            maxProfit += (currentPrice - previousPrice);
        }
    }

    return maxProfit;
};

參考資料