LeetCode力扣 122. 买卖股票的最佳时机 II Best Time to Buy and Sell Stock II 题解代码 JavaScript

问题 https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/

练习使用JavaScript解答

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    if(prices.length < 2)
        return 0;
    var arr = [];
    var i,j,tmp,tmpM;
    arr[prices.length] = 0;
    arr[prices.length - 1] = 0;
    for(i = prices.length - 2; i >= 0; --i) {
        tmpM = 0;
        for(j = i+1; j < prices.length; ++j) {
            tmp = (prices[j] - prices[i])>0 ? prices[j] - prices[i] : 0;
            if(tmpM < tmp + arr[j+1])
                tmpM = tmp + arr[j+1];
        }
        arr[i] = tmpM > arr[i+1] ? tmpM : arr[i+1];
    }
    return arr[0];
};

时间复杂度O(n2),空间复杂度O(n)

你可能感兴趣的:(LeetCode力扣 122. 买卖股票的最佳时机 II Best Time to Buy and Sell Stock II 题解代码 JavaScript)