Skip to content

Commit 5f6e893

Browse files
committed
add stock trading DP solution
1 parent dd148c2 commit 5f6e893

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

_posts/coding/summary/dynamic_prog/2021-01-01-dp-state-machine.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,4 +217,23 @@ int maxProfit_k_2(int[] prices) {
217217
}
218218
return dp_i20;
219219
}
220+
```
221+
222+
## 188. k = any integer
223+
224+
```java
225+
int maxProfit_k_any(int max_k, int[] prices) {
226+
int n = prices.length;
227+
if (max_k > n / 2)
228+
return maxProfit_k_inf(prices);
229+
230+
int[][][] dp = new int[n][max_k + 1][2];
231+
for (int i = 0; i < n; i++)
232+
for (int k = max_k; k >= 1; k--) {
233+
if (i - 1 == -1) { /* 处理 base case */ }
234+
dp[i][k][0] = max(dp[i-1][k][0], dp[i-1][k][1] + prices[i]);
235+
dp[i][k][1] = max(dp[i-1][k][1], dp[i-1][k-1][0] - prices[i]);
236+
}
237+
return dp[n - 1][max_k][0];
238+
}
220239
```

0 commit comments

Comments
 (0)