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: