11. The best time to buy and sell stocks Ⅲ

Subject description:

Given an array, which i-th element is the price of a given stock i-th day.
Design an algorithm to compute the maximum profit you can get. You can complete up to two transactions.
Note: You can not simultaneously involved in multiple transactions (you must sell before buying shares again before the fall).
Example 1:

输入: [3,3,5,0,0,3,1,4]
输出: 6
解释: 在第 4 天(股票价格 = 0)的时候买入,在第 6 天(股票价格 = 3)的时候卖出,这笔交易所能获得利润 = 3-0 = 3 。
     随后,在第 7 天(股票价格 = 1)的时候买入,在第 8 天 (股票价格 = 4)的时候卖出,这笔交易所能获得利润 = 4-1 = 3

Code:

JavaScript

  • Violence, direct dry on the end, first find out at the halfway point, that is the day before and after, respectively, buy the stock, then the first question of the form to find out the maximum value, respectively.
  • Time complexity: O (n ^ 2).
/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    var temp = 0
    for (var i = 1; i < prices.length; i++ ) {
        var res1 = 0
        var min1 = prices[0]
        for (var j = 0; j <= i; j++ ) {
            if (prices[j] < min1) {
                min1 = prices[j]
            } else if (prices[j] - min1 > res1) {
                res1 = prices[j] - min1
            }
        }
        var res2 = 0
        var min2 = prices[i]
        for (var k = i; k < prices.length; k++ ) {
            if (prices[k] < min2) {
                min2 = prices[k]
            } else if (prices[k] - min2 > res2) {
                res2 = prices[k] - min2
            }
        }
        temp = Math.max(temp , res1 + res2)
    }
    return temp
};

Here Insert Picture Description
Violence memory consumption is still small. . . .

  • Dynamic programming, did not think that he is just beginning to feel the time complexity of this question will also be able to shrink O (n ^ 2), and it seems smart people everywhere ah, learning to learn, by look solution to a problem bigwigs that he wrote about.
  • General idea: just look at this time of the solution to a problem to be shocked, really is a very clever way, by the contents of the loop so that buy1, sell1, buy2, sell2 must be done in sequential order.
  • Time complexity: O (n).
/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    var buy1 = -prices[0], sell1 = 0
    var buy2 = -prices[0], sell2 = 0
    for (var i = 1; i < prices.length; i++ ) {     
        buy1 = Math.max(buy1, -prices[i])
        sell1 = Math.max(sell1, prices[i] + buy1)
        buy2 = Math.max(buy2, sell1 - prices[i])
        sell2 = Math.max(sell2, buy2 + prices[i])        
    }
    return sell2
};

Here Insert Picture Description

Published 14 original articles · won praise 1 · views 1698

Guess you like

Origin blog.csdn.net/weixin_45569004/article/details/104693509