From f8fbdd4ed1d66bf03578728650310bddc8a5fc7a Mon Sep 17 00:00:00 2001 From: Wen Date: Sun, 7 Nov 2021 12:53:27 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=200714.=E4=B9=B0=E5=8D=96?= =?UTF-8?q?=E8=82=A1=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BA?= =?UTF-8?q?=E5=90=AB=E6=89=8B=E7=BB=AD=E8=B4=B9=EF=BC=88=E5=8A=A8=E6=80=81?= =?UTF-8?q?=E8=A7=84=E5=88=92=EF=BC=89.md=20Go=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...佳时机含手续费(动态规划).md | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/problems/0714.买卖股票的最佳时机含手续费(动态规划).md b/problems/0714.买卖股票的最佳时机含手续费(动态规划).md index 50db8868..42afd777 100644 --- a/problems/0714.买卖股票的最佳时机含手续费(动态规划).md +++ b/problems/0714.买卖股票的最佳时机含手续费(动态规划).md @@ -152,6 +152,37 @@ class Solution: ``` Go: +```go +// 买卖股票的最佳时机含手续费 动态规划 +// 时间复杂度O(n) 空间复杂度O(n) +func maxProfit(prices []int, fee int) int { + if len(prices) == 1 { + return 0 + } + + dp := make([][]int, len(prices)) + status := make([]int, len(prices) * 2) + for i := range dp { + dp[i] = status[:2] + status = status[2:] + } + dp[0][0] = -prices[0] + + for i := 1; i < len(dp); i++ { + dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i]) + dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i] - fee) + } + + return dp[len(dp) - 1][1] +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` Javascript: ```javascript