Sponsored
Sponsored
In this approach, we use Dynamic Programming to manage two states: whether you're holding a stock or not on each day. The goal is to maximize the profit by deciding to buy, sell, or hold at each step while accounting for the transaction fee.
States: We define two states: hold[i]
which represents the maximum profit you can have on day i when holding a stock, and cash[i]
which represents the maximum profit on day i when not holding a stock.
State Transitions: On each day, you can either buy a stock (thus moving from cash[i-1]
to hold[i]
) or sell a stock (thus moving from hold[i-1]
to cash[i]
). Decisions should include transaction fee accordingly.
Time Complexity: O(N), where N is the number of days, since we go through the prices once.
Space Complexity: O(1), as we use a fixed amount of extra space regardless of input size.
1class Solution:
2 def maxProfit(self, prices, fee):
3 cash, hold = 0, -prices[0]
4 for i in
The Python solution uses two variables, cash
and hold
, initialized appropriately to represent no stock and bought stock states respectively. On each day, the optimal choice between selling and holding, or buying and holding, is computed using the max
function, ensuring maximum profit accounting for the transaction fee.
The greedy approach is an alternative solution that strives to maximize the profit by considering local optimal decisions. Unlike the dynamic approach that tracks two states, this method attempts to buy on dips and sell at peaks whenever possible while covering the transaction fee.
Keep track of the lowest price at which a stock might have been bought, and compare future prices to decide if selling should occur, adjusting the buy price to be less the transaction fee.
Time Complexity: O(N), since it processes each price once.
Space Complexity: O(1), using a constant set of additional variables.
Java's implementation uses a for
loop over the price array, keeping track of the current minimum price at which buying/selling leads to profit. Transaction fees are integrated to update potential profits.