#714

Best Time to Buy and Sell Stock with Transaction Fee

Medium
ArrayDynamic ProgrammingGreedyDynamic ProgrammingGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses dynamic programming to keep track of two states: the maximum profit when holding a stock and when not holding a stock. This allows us to efficiently calculate the maximum profit without redundant calculations.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize two variables: cash (profit when not holding a stock) and hold (profit when holding a stock). Set cash to 0 and hold to negative infinity.
  2. 2Step 2: Iterate through each price in the prices array.
  3. 3Step 3: Update the cash to be the maximum of its current value and hold plus the current price minus the fee (selling the stock).
  4. 4Step 4: Update the hold to be the maximum of its current value and cash minus the current price (buying the stock).
  5. 5Step 5: After iterating through all prices, cash will contain the maximum profit.
solution.py12 lines
1# Full working Python code
2prices = [1, 3, 2, 8, 4, 9]
3fee = 2
4
5def maxProfit(prices, fee):
6    cash, hold = 0, float('-inf')
7    for price in prices:
8        cash = max(cash, hold + price - fee)
9        hold = max(hold, cash - price)
10    return cash
11
12print(maxProfit(prices, fee))

Complexity note: The time complexity is O(n) because we only iterate through the prices array once. The space complexity is O(1) since we are using a constant amount of space for the cash and hold variables.

  • 1Understanding the difference between holding and not holding stock is crucial.
  • 2Dynamic programming allows us to avoid redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.