Skip to content

Commit 8b2705f

Browse files
authored
修正"需要冷却期的股票交易"算法,将意义不明的s1状态并入“buy”状态
原解答状态转移图列出四个状态,实际上三个就够了(将意义不明的s1状态并入“buy”状态)
1 parent f84b140 commit 8b2705f

File tree

1 file changed

+13
-12
lines changed

1 file changed

+13
-12
lines changed

notes/Leetcode 题解 - 动态规划.md

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1055,27 +1055,28 @@ public int combinationSum4(int[] nums, int target) {
10551055

10561056
题目描述:交易之后需要有一天的冷却时间。
10571057

1058-
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/ffd96b99-8009-487c-8e98-11c9d44ef14f.png" width="300px"> </div><br>
1058+
1059+
该题为马尔可夫过程,分为A观望,B持股,C冷却三个状态
1060+
状态转移图:A-(观望)->A, A-(买入)->B, B-(观望)->B, B-(卖出)->C, C-(冷却)->A
1061+
可用维特比算法求解
10591062

10601063
```java
10611064
public int maxProfit(int[] prices) {
10621065
if (prices == null || prices.length == 0) {
10631066
return 0;
10641067
}
10651068
int N = prices.length;
1066-
int[] buy = new int[N];
1067-
int[] s1 = new int[N];
1068-
int[] sell = new int[N];
1069-
int[] s2 = new int[N];
1070-
s1[0] = buy[0] = -prices[0];
1071-
sell[0] = s2[0] = 0;
1069+
int[] A = new int[N];
1070+
int[] B = new int[N];
1071+
int[] C = new int[N];
1072+
A[0] = 0;
1073+
B[0] = C[0] = -prices[0];
10721074
for (int i = 1; i < N; i++) {
1073-
buy[i] = s2[i - 1] - prices[i];
1074-
s1[i] = Math.max(buy[i - 1], s1[i - 1]);
1075-
sell[i] = Math.max(buy[i - 1], s1[i - 1]) + prices[i];
1076-
s2[i] = Math.max(s2[i - 1], sell[i - 1]);
1075+
A[i] = Math.max(A[i - 1], C[i - 1]);
1076+
B[i] = Math.max(B[i - 1], A[i - 1] - prices[i]);
1077+
C[i] = B[i - 1] + prices[i];
10771078
}
1078-
return Math.max(sell[N - 1], s2[N - 1]);
1079+
return Math.max(A[N - 1], C[N - 1]);
10791080
}
10801081
```
10811082

0 commit comments

Comments
 (0)