From 77e75035d321ff39dc0cf30b2a1e02c6f87edfbb Mon Sep 17 00:00:00 2001 From: jojoo15 <75017412+jojoo15@users.noreply.github.com> Date: Fri, 9 Jul 2021 10:39:19 +0200 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=200188=20=E4=B9=B0=E8=82=A1?= =?UTF-8?q?=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BAIV=20pyth?= =?UTF-8?q?on3=E7=89=88=E6=9C=AC=E4=BA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加 0188 买股票的最佳时机IV python3版本二 --- .../0188.买卖股票的最佳时机IV.md | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/problems/0188.买卖股票的最佳时机IV.md b/problems/0188.买卖股票的最佳时机IV.md index 431c292b..daaed8a9 100644 --- a/problems/0188.买卖股票的最佳时机IV.md +++ b/problems/0188.买卖股票的最佳时机IV.md @@ -211,7 +211,7 @@ class Solution { //动态规划 Python: - +版本一 ```python class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: @@ -226,7 +226,22 @@ class Solution: dp[i][j+2] = max(dp[i-1][j+2], dp[i-1][j+1] + prices[i]) return dp[-1][2*k] ``` - +版本二 +```python3 +class Solution: + def maxProfit(self, k: int, prices: List[int]) -> int: + if len(prices) == 0: return 0 + dp = [0] * (2*k + 1) + for i in range(1,2*k,2): + dp[i] = -prices[0] + for i in range(1,len(prices)): + for j in range(1,2*k + 1): + if j % 2: + dp[j] = max(dp[j],dp[j-1]-prices[i]) + else: + dp[j] = max(dp[j],dp[j-1]+prices[i]) + return dp[2*k] +``` Go: