最佳买卖股票时间 II

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

找到你能获取的最大收益。你可以按你喜欢的方式进行多次交易(多次买入和卖出同一只股票)。

注意: 你不能同时进行多项交易(即你在买入之前要先把之前的持有的股票卖出)。

Example 1:

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.

Example 2:

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.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e., max profit = 0.

限制:

  • 1 <= prices.length <= 3 * 104
  • 0 <= prices[i] <= 104

解法 根据股价和时间建立平面直角坐标系,画出股价折线图,会发现最大收益是在波谷买入,然后在波峰买出,所以根据数据的上升/下降趋势进行对应的操作即可得到最大收益。

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    // let lastBuyPrice = 0; // 上次买入价格,0 表示未持股,约束条件表明股价有可能出现 0,开始没注意到,导致第一次提交没过
    let lastBuyPrice = null; // 上次买入价格,null 表示未持股
    let maxProfit = 0; // 历史最大收益
    
    for (let i = 0; i < prices.length; ++i) {
        const currPrice = prices[i];
        const nextPrice = prices[i + 1];

        // 最后一天的情况处理一下,将之前上升或者持平导致没卖出的都卖掉
        if (i === (prices.length - 1) && lastBuyPrice !== null) {
            maxProfit += currPrice - lastBuyPrice;
            break;
        }
        
        // 即将下降,如果持有则卖出
        if (currPrice > nextPrice && lastBuyPrice !== null) {
            maxProfit += currPrice - lastBuyPrice;
            lastBuyPrice = null;
        }

        // 即将上升,如果未持有则买入
        if (currPrice < nextPrice && lastBuyPrice === null) {
            lastBuyPrice = currPrice;
        }

    }

    return maxProfit;
};