Leetcode - Insert Delete GetRandom O(1)
Leetcode - Best Time to Buy and Sell Stock IV

Leetcode - Best Time to Buy and Sell Stock III

violet posted @ Jun 16, 2020 01:37:41 AM in 算法 with tags Algorithm DP Golang , 400 阅读

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

Input: [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
             Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.

 

func maxProfit(prices []int) int {
    if len(prices) == 0 {
        return 0
    }
    dp := make([][]int, 3)
    n := len(prices)
    for i := 0; i < len(dp); i++ {
        dp[i] = make([]int, n)
    }
    for k := 1; k <= 2; k++ {
        for i := 1; i < n; i++ {
            minP := prices[0]
            for j := 1; j <= i; j++ {
                minP = min(minP, prices[j] - dp[k-1][j-1])
            }
            dp[k][i] = max(dp[k][i-1], prices[i]-minP)
        }
    }
    return dp[2][n-1]
}

func min(a, b int) int {
    if a < b {
        return a
    }
    return b
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter