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

参考资料