algoadvance

The problem is to determine the maximum profit you can achieve from trading a stock, given a transaction fee. Specifically:

The goal is to maximize your profit.

Here is the function signature:

def maxProfit(prices: List[int], fee: int) -> int:

Clarifying Questions

  1. Types and constraints: What are the constraints on the size of the prices array, and the values of the prices and the fee?
    • Typically, 1 <= prices.length <= 10^5
    • 1 <= prices[i], fee <= 10^4
  2. Edge Cases: What should be the output when there are no prices or when trading is not feasible (e.g., all prices are the same)?

Strategy

We will use a dynamic programming approach to solve this problem.

Key Concepts:

  1. Hold State: Represents the maximum profit obtainable on day i if we hold a stock.
  2. Cash State: Represents the maximum profit obtainable on day i if we do not hold a stock (i.e., we are in “cash”).

Let’s initialize two arrays:

Recurrence Relations:

Initialization:

Coding the Solution

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]

Time Complexity

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.

Try our interview co-pilot at AlgoAdvance.com