Skip to content

Commit 7858dac

Browse files
authored
简化”需要交易费用的股票交易“题解,删除不必要的s状态
原图画了四个状态实在没有必要,只需要两个状态
1 parent 8b2705f commit 7858dac

File tree

1 file changed

+11
-13
lines changed

1 file changed

+11
-13
lines changed

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

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1057,7 +1057,7 @@ public int combinationSum4(int[] nums, int target) {
10571057

10581058

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

10631063
```java
@@ -1099,24 +1099,22 @@ The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
10991099

11001100
题目描述:每交易一次,都要支付一定的费用。
11011101

1102-
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/1e2c588c-72b7-445e-aacb-d55dc8a88c29.png" width="300px"> </div><br>
1102+
1103+
分为A观望,B持股,两个状态
1104+
状态转移图:A-(观望)->A, A-(买入|-price)->B, B-(观望)->B, B-(卖出|+price|-fee)->A
11031105

11041106
```java
11051107
public int maxProfit(int[] prices, int fee) {
11061108
int N = prices.length;
1107-
int[] buy = new int[N];
1108-
int[] s1 = new int[N];
1109-
int[] sell = new int[N];
1110-
int[] s2 = new int[N];
1111-
s1[0] = buy[0] = -prices[0];
1112-
sell[0] = s2[0] = 0;
1109+
int[] A = new int[N];
1110+
int[] B = new int[N];
1111+
A[0] = 0;
1112+
B[0] = -prices[0];
11131113
for (int i = 1; i < N; i++) {
1114-
buy[i] = Math.max(sell[i - 1], s2[i - 1]) - prices[i];
1115-
s1[i] = Math.max(buy[i - 1], s1[i - 1]);
1116-
sell[i] = Math.max(buy[i - 1], s1[i - 1]) - fee + prices[i];
1117-
s2[i] = Math.max(s2[i - 1], sell[i - 1]);
1114+
A[i] = Math.max(A[i - 1], B[i - 1] + prices[i] -fee);
1115+
B[i] = Math.max(A[i - 1] - prices[i], B[i - 1]);
11181116
}
1119-
return Math.max(sell[N - 1], s2[N - 1]);
1117+
return A[N - 1];
11201118
}
11211119
```
11221120

0 commit comments

Comments
 (0)