The problem is to determine the maximum profit you can achieve from trading a stock, given a transaction fee. Specifically:
prices
where prices[i]
is the price of a given stock on the i-th
day.The goal is to maximize your profit.
Here is the function signature:
def maxProfit(prices: List[int], fee: int) -> int:
prices
array, and the values of the prices and the fee?
prices.length
<= 10^5prices[i]
, fee
<= 10^4We will use a dynamic programming approach to solve this problem.
i
if we hold a stock.i
if we do not hold a stock (i.e., we are in “cash”).Let’s initialize two arrays:
hold[i]
: Maximum profit on day i
if we are holding a stock.cash[i]
: Maximum profit on day i
if we are not holding a stock.cash[i] = max(cash[i-1], hold[i-1] + prices[i] - fee)
cash[i-1]
).hold[i-1] + prices[i] - fee
).hold[i] = max(hold[i-1], cash[i-1] - prices[i])
hold[i-1]
).prices[i]
and taking from cash[i-1]
).cash[0] = 0
(If we do nothing on the first day).hold[0] = -prices[0]
(If we buy the stock on the first day).def maxProfit(prices, fee):
n = len(prices)
if n == 0:
return 0
# Initialize the state variables
cash = [0] * n
hold = [0] * n
# Initialize the first day states
cash[0] = 0
hold[0] = -prices[0]
for i in range(1, n):
# Calculate cash and hold states for day i
cash[i] = max(cash[i-1], hold[i-1] + prices[i] - fee)
hold[i] = max(hold[i-1], cash[i-1] - prices[i])
# The maximum profit on the last day without holding a stock
return cash[-1]
O(n)
where n
is the length of the prices
array, as we iterate through the array once.O(1)
since we only need to keep track of the current and previous states.We can implement space optimization as follows:
def maxProfit(prices, fee):
n = len(prices)
if n == 0:
return 0
# Initialize the state variables for day 0
cash = 0
hold = -prices[0]
for i in range(1, n):
# Calculate today's states and update the variables
new_cash = max(cash, hold + prices[i] - fee)
new_hold = max(hold, cash - prices[i])
# Update states
cash = new_cash
hold = new_hold
# The maximum profit on the last day without holding a stock
return cash
This final version effectively uses O(1)
space.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?