|
40 | 40 |
|
41 | 41 | ## Solutions
|
42 | 42 |
|
| 43 | +**Solution 1: Memoization Search** |
| 44 | + |
| 45 | +We design a function $dfs(i, j)$, which represents the maximum profit that can be obtained starting from the $i$th day with state $j$. The values of $j$ are $0$ and $1$, respectively representing currently not holding a stock and holding a stock. The answer is $dfs(0, 0)$. |
| 46 | + |
| 47 | +The execution logic of the function $dfs(i, j)$ is as follows: |
| 48 | + |
| 49 | +If $i \geq n$, it means that there are no more stocks to trade, so return $0$; |
| 50 | + |
| 51 | +Otherwise, we can choose not to trade, then $dfs(i, j) = dfs(i + 1, j)$. We can also trade stocks. If $j > 0$, it means that we currently hold a stock and can sell it, then $dfs(i, j) = prices[i] + dfs(i + 2, 0)$. If $j = 0$, it means that we currently do not hold a stock and can buy, then $dfs(i, j) = -prices[i] + dfs(i + 1, 1)$. Take the maximum value as the return value of the function $dfs(i, j)$. |
| 52 | + |
| 53 | +The answer is $dfs(0, 0)$. |
| 54 | + |
| 55 | +To avoid repeated calculations, we use the method of memoization search, and use an array $f$ to record the return value of $dfs(i, j)$. If $f[i][j]$ is not $-1$, it means that it has been calculated, and we can directly return $f[i][j]$. |
| 56 | + |
| 57 | +The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $prices$. |
| 58 | + |
| 59 | +**Solution 2: Dynamic Programming** |
| 60 | + |
| 61 | +We can also use dynamic programming to solve this problem. |
| 62 | + |
| 63 | +We define $f[i][j]$ to represent the maximum profit that can be obtained on the $i$th day with state $j$. The values of $j$ are $0$ and $1$, respectively representing currently not holding a stock and holding a stock. Initially, $f[0][0] = 0$, $f[0][1] = -prices[0]$. |
| 64 | + |
| 65 | +When $i \geq 1$, if we currently do not hold a stock, then $f[i][0]$ can be obtained by transitioning from $f[i - 1][0]$ and $f[i - 1][1] + prices[i]$, i.e., $f[i][0] = \max(f[i - 1][0], f[i - 1][1] + prices[i])$. If we currently hold a stock, then $f[i][1]$ can be obtained by transitioning from $f[i - 1][1]$ and $f[i - 2][0] - prices[i]$, i.e., $f[i][1] = \max(f[i - 1][1], f[i - 2][0] - prices[i])$. The final answer is $f[n - 1][0]$. |
| 66 | + |
| 67 | +The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $prices$. |
| 68 | + |
| 69 | +We notice that the transition of state $f[i][]$ is only related to $f[i - 1][]$ and $f[i - 2][0]$, so we can use three variables $f$, $f_0$, $f_1$ to replace the array $f$, optimizing the space complexity to $O(1)$. |
| 70 | + |
43 | 71 | <!-- tabs:start -->
|
44 | 72 |
|
45 | 73 | ### **Python3**
|
|
0 commit comments