Skip to content

Commit

Permalink
修正"需要冷却期的股票交易"算法,将意义不明的s1状态并入“buy”状态
Browse files Browse the repository at this point in the history
原解答状态转移图列出四个状态,实际上三个就够了(将意义不明的s1状态并入“buy”状态)
  • Loading branch information
somone23412 authored Feb 12, 2020
1 parent f84b140 commit 8b2705f
Showing 1 changed file with 13 additions and 12 deletions.
25 changes: 13 additions & 12 deletions notes/Leetcode 题解 - 动态规划.md
Original file line number Diff line number Diff line change
Expand Up @@ -1055,27 +1055,28 @@ public int combinationSum4(int[] nums, int target) {

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

<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/ffd96b99-8009-487c-8e98-11c9d44ef14f.png" width="300px"> </div><br>

该题为马尔可夫过程分为A观望B持股C冷却三个状态
状态转移图A-(观望)->A, A-(买入)->B, B-(观望)->B, B-(卖出)->C, C-(冷却)->A
可用维特比算法求解

```java
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) {
return 0;
}
int N = prices.length;
int[] buy = new int[N];
int[] s1 = new int[N];
int[] sell = new int[N];
int[] s2 = new int[N];
s1[0] = buy[0] = -prices[0];
sell[0] = s2[0] = 0;
int[] A = new int[N];
int[] B = new int[N];
int[] C = new int[N];
A[0] = 0;
B[0] = C[0] = -prices[0];
for (int i = 1; i < N; i++) {
buy[i] = s2[i - 1] - prices[i];
s1[i] = Math.max(buy[i - 1], s1[i - 1]);
sell[i] = Math.max(buy[i - 1], s1[i - 1]) + prices[i];
s2[i] = Math.max(s2[i - 1], sell[i - 1]);
A[i] = Math.max(A[i - 1], C[i - 1]);
B[i] = Math.max(B[i - 1], A[i - 1] - prices[i]);
C[i] = B[i - 1] + prices[i];
}
return Math.max(sell[N - 1], s2[N - 1]);
return Math.max(A[N - 1], C[N - 1]);
}
```

Expand Down

0 comments on commit 8b2705f

Please sign in to comment.