From ed2588520a9e6822e110995baa34c7d278c26204 Mon Sep 17 00:00:00 2001 From: roylx <73628821+roylx@users.noreply.github.com> Date: Mon, 14 Nov 2022 15:00:07 -0700 Subject: [PATCH] =?UTF-8?q?Update=200121.=E4=B9=B0=E5=8D=96=E8=82=A1?= =?UTF-8?q?=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BA.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加了python 动态规划:版本三 --- problems/0121.买卖股票的最佳时机.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/problems/0121.买卖股票的最佳时机.md b/problems/0121.买卖股票的最佳时机.md index 63ac5d04..cf17f48d 100644 --- a/problems/0121.买卖股票的最佳时机.md +++ b/problems/0121.买卖股票的最佳时机.md @@ -310,6 +310,18 @@ class Solution: return dp[(length-1) % 2][1] ``` +> 动态规划:版本三 +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + length = len(prices) + dp0, dp1 = -prices[0], 0 #注意这里只维护两个常量,因为dp0的更新不受dp1的影响 + for i in range(1, length): + dp1 = max(dp1, dp0 + prices[i]) + dp0 = max(dp0, -prices[i]) + return dp1 +``` + Go: > 贪心法: ```Go