Best Time to Buy and Sell Stock V Problem
Description
LeetCode Problem 3573.
You are given an integer array prices where prices[i] is the price of a stock in dollars on the i^th day, and an integer k.
You are allowed to make at most k transactions, where each transaction can be either of the following:
- Normal transaction: Buy on day
i, then sell on a later dayjwherei < j. You profitprices[j] - prices[i]. - Short selling transaction: Sell on day
i, then buy back on a later dayjwherei < j. You profitprices[i] - prices[j].
Note that you must complete each transaction before starting another. Additionally, you can't buy or sell on the same day you are selling or buying back as part of a previous transaction.
Return the maximum total profit you can earn by making at most k transactions.
Example 1:
Input: prices = [1,7,9,8,2], k = 2
Output: 14
Explanation:
We can make $14 of profit through 2 transactions:
- A normal transaction: buy the stock on day 0 for $1 then sell it on day 2 for $9.
- A short selling transaction: sell the stock on day 3 for $8 then buy back on day 4 for $2.
Example 2:
Input: prices = [12,16,19,19,8,1,19,13,9], k = 3
Output: 36
Explanation:
We can make $36 of profit through 3 transactions:
- A normal transaction: buy the stock on day 0 for $12 then sell it on day 2 for $19.
- A short selling transaction: sell the stock on day 3 for $19 then buy back on day 4 for $8.
- A normal transaction: buy the stock on day 5 for $1 then sell it on day 6 for $19.
Constraints:
2 <= prices.length <= 10^31 <= prices[i] <= 10^91 <= k <= prices.length / 2
Solution
Approach: Dynamic Programming
A transaction is either a normal one (buy, then sell later) or a short one (sell first, then buy back later). Let f[i][j][s] be the best profit after day i with j transactions started, where s is 0 when no position is open, 1 when holding a stock, and 2 when in a short position.
Start with f[0][j][1] = -prices[0] (buy on day 0) and f[0][j][2] = prices[0] (short on day 0), and 0 for s = 0. For the next days:
f[i][j][0] = max(f[i-1][j][0], f[i-1][j][1] + prices[i], f[i-1][j][2] - prices[i])(stay flat, sell the stock, or buy back the short).f[i][j][1] = max(f[i-1][j][1], f[i-1][j-1][0] - prices[i])(keep holding, or buy today).f[i][j][2] = max(f[i-1][j][2], f[i-1][j-1][0] + prices[i])(keep the short, or open one today).
The answer is f[n-1][k][0].
Complexity: time O(n k), space O(n k), where n is the number of days.
class Solution:
def maximumProfit(self, prices: List[int], k: int) -> int:
n = len(prices)
f = [[[0] * 3 for _ in range(k + 1)] for _ in range(n)]
for j in range(1, k + 1):
f[0][j][1] = -prices[0]
f[0][j][2] = prices[0]
for i in range(1, n):
for j in range(1, k + 1):
f[i][j][0] = max(
f[i - 1][j][0],
f[i - 1][j][1] + prices[i],
f[i - 1][j][2] - prices[i],
)
f[i][j][1] = max(f[i - 1][j][1], f[i - 1][j - 1][0] - prices[i])
f[i][j][2] = max(f[i - 1][j][2], f[i - 1][j - 1][0] + prices[i])
return f[n - 1][k][0]