From 30886018c4fc1174914a7db707c15879fc9c6392 Mon Sep 17 00:00:00 2001 From: LiHua <1985390347@qq.com> Date: Wed, 24 Nov 2021 16:12:39 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86309=E5=92=8C714?= =?UTF-8?q?=E8=82=A1=E7=A5=A8=E9=97=AE=E9=A2=98=E4=B8=80=E7=BB=B4=E6=95=B0?= =?UTF-8?q?=E7=BB=84=E4=BC=98=E5=8C=96=E7=A9=BA=E9=97=B4=E7=9A=84java?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...09.最佳买卖股票时机含冷冻期.md | 23 +++++++++++++++++++ ...买卖股票的最佳时机含手续费.md | 18 +++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/problems/0309.最佳买卖股票时机含冷冻期.md b/problems/0309.最佳买卖股票时机含冷冻期.md index 8520e655..8c6ab288 100644 --- a/problems/0309.最佳买卖股票时机含冷冻期.md +++ b/problems/0309.最佳买卖股票时机含冷冻期.md @@ -185,6 +185,29 @@ class Solution { } ``` +```java +// 一维数组优化 +class Solution { + public int maxProfit(int[] prices) { + // dp[2]和dp[3]用来存储冷冻期的数据 + int[] dp=new int[4]; + // 0表示持有,1表示卖出 + dp[0] = -prices[0]; + dp[1] = 0; + for(int i = 1; i <= prices.length; i++){ + // 使用临时变量来保存dp[0], dp[2] + // 因为马上dp[0]和dp[2]的数据都会变 + int temp = dp[0]; + int temp1 = dp[2]; + dp[0] = Math.max(dp[0], Math.max(dp[3], dp[1]) - prices[i-1]); + dp[1] = Math.max(dp[1], dp[3]); + dp[2] = temp + prices[i-1]; + dp[3] = temp1; + } + return Math.max(dp[3],Math.max(dp[1],dp[2])); + } +} +``` Python: diff --git a/problems/0714.买卖股票的最佳时机含手续费.md b/problems/0714.买卖股票的最佳时机含手续费.md index afa2e2f6..964d5ea9 100644 --- a/problems/0714.买卖股票的最佳时机含手续费.md +++ b/problems/0714.买卖股票的最佳时机含手续费.md @@ -195,8 +195,26 @@ class Solution { // 动态规划 } ``` +```java +// 一维数组优化 +class Solution { + public int maxProfit(int[] prices, int fee) { + int[] dp = new int[2]; + dp[0] = -prices[0]; + dp[1] = 0; + for (int i = 1; i <= prices.length; i++) { + dp[0] = Math.max(dp[0], dp[1] - prices[i - 1]); + dp[1] = Math.max(dp[1], dp[0] + prices[i - 1] - fee); + } + return dp[1]; + } +} +``` + + Python: + ```python class Solution: # 贪心思路 def maxProfit(self, prices: List[int], fee: int) -> int: