@@ -1055,27 +1055,28 @@ public int combinationSum4(int[] nums, int target) {
1055
1055
1056
1056
题目描述:交易之后需要有一天的冷却时间。
1057
1057
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-(买入|-price)->B, B-(观望)->B, B-(卖出|+price)->C, C-(冷却)->A
1061
+ 可用维特比算法求解
1059
1062
1060
1063
``` java
1061
1064
public int maxProfit(int [] prices) {
1062
1065
if (prices == null || prices. length == 0 ) {
1063
1066
return 0 ;
1064
1067
}
1065
1068
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 ];
1072
1074
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];
1077
1078
}
1078
- return Math . max(sell [N - 1 ], s2 [N - 1 ]);
1079
+ return Math . max(A [N - 1 ], C [N - 1 ]);
1079
1080
}
1080
1081
```
1081
1082
@@ -1098,24 +1099,22 @@ The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
1098
1099
1099
1100
题目描述:每交易一次,都要支付一定的费用。
1100
1101
1101
- <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
1102
1105
1103
1106
``` java
1104
1107
public int maxProfit(int [] prices, int fee) {
1105
1108
int N = prices. length;
1106
- int [] buy = new int [N ];
1107
- int [] s1 = new int [N ];
1108
- int [] sell = new int [N ];
1109
- int [] s2 = new int [N ];
1110
- s1[0 ] = buy[0 ] = - prices[0 ];
1111
- 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 ];
1112
1113
for (int i = 1 ; i < N ; i++ ) {
1113
- buy[i] = Math . max(sell[i - 1 ], s2[i - 1 ]) - prices[i];
1114
- s1[i] = Math . max(buy[i - 1 ], s1[i - 1 ]);
1115
- sell[i] = Math . max(buy[i - 1 ], s1[i - 1 ]) - fee + prices[i];
1116
- 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 ]);
1117
1116
}
1118
- return Math . max(sell [N - 1 ], s2[ N - 1 ]) ;
1117
+ return A [N - 1 ];
1119
1118
}
1120
1119
```
1121
1120
0 commit comments