You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: solution/3500-3599/3573.Best Time to Buy and Sell Stock V/README_EN.md
+145-4Lines changed: 145 additions & 4 deletions
Original file line number
Diff line number
Diff line change
@@ -80,32 +80,173 @@ We can make $36 of profit through 3 transactions:
80
80
81
81
<!-- solution:start -->
82
82
83
-
### Solution 1
83
+
### Solution 1: Dynamic Programming
84
+
85
+
We define $f[i][j][k]$ to represent the maximum profit on the first $i$ days, with at most $j$ transactions, and the current state $k$. Here, the state $k$ has three possibilities:
86
+
87
+
- If $k = 0$, it means we do not hold any stock.
88
+
- If $k = 1$, it means we are holding a stock.
89
+
- If $k = 2$, it means we are holding a short position.
90
+
91
+
Initially, for any $j \in [1, k]$, we have $f[0][j][1] = -prices[0]$ and $f[0][j][2] = prices[0]$. This means buying a stock or opening a short position on day 0.
92
+
93
+
Next, we update $f[i][j][k]$ using state transitions. For each day $i$ and each transaction $j$, we update according to the current state $k$:
94
+
95
+
- If $k = 0$, meaning no stock is held, this state can be reached from three situations:
96
+
- No stock was held the previous day.
97
+
- A stock was held the previous day and sold today.
98
+
- A short position was held the previous day and bought back today.
99
+
- If $k = 1$, meaning a stock is held, this state can be reached from two situations:
100
+
- A stock was held the previous day.
101
+
- No stock was held the previous day and a stock is bought today.
102
+
- If $k = 2$, meaning a short position is held, this state can be reached from two situations:
103
+
- A short position was held the previous day.
104
+
- No stock was held the previous day and a short position is opened (sold) today.
105
+
106
+
That is, for $1 \leq i < n$ and $1 \leq j \leq k$, we have the following state transition equations:
Finally, we return $f[n - 1][k][0]$, which is the maximum profit after at most $k$ transactions and not holding any stock at the end of $n$ days.
117
+
118
+
The time complexity is $O(n \times k)$, and the space complexity is $O(n \times k)$, where $n$ is the length of the array $\textit{prices}$ and $k$ is the maximum number of transactions.
0 commit comments