LeetCode 714. Best Time to Buy and Sell Stock with Transaction Fee

Post by ailswan June. 29, 2024

714. Best Time to Buy and Sell Stock with Transaction Fee

Problem Statement

link: LeetCode.cn LeetCode Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer.

The algorithm for myAtoi(string s) is as follows:

Whitespace: Ignore any leading whitespace (“ “). You are given an array prices where prices[i] is the price of a given stock on the ith day, and an integer fee representing a transaction fee.

Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.

Note:

You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). The transaction fee is only charged once for each stock purchase and sale.

Example:

Input: prices = [1,3,2,8,4,9], fee = 2 Output: 8

Input: prices = [1,3,7,5,10,3], fee = 3 Output: 6

Solution Approach

The solution uses dynamic programming to track the maximum profit for each day, with two states: one for holding a stock and one for not holding a stock, while considering the transaction fee during each sell operation.

Algorithm

  1. State Representation: Use two states, cash and hold, where cash represents the maximum profit without holding any stock, and hold represents the maximum profit while holding a stock.
  2. State Transitions: Update the states for each day by either selling the stock (considering the transaction fee) or holding/buying a new stock based on the maximum profit calculated so far.
  3. Initialization and Iteration: Initialize the states with no initial profit and the first day’s purchase, then iterate through the prices to update the states, finally returning the maximum profit in the cash state at the end.

Implement

    class Solution:
    def maxProfit(self, prices: List[int], fee: int) -> int:
        #cash[i]
        #hold[i]
        #cash[i] = max(cash[i - 1], hold[i - 1] + price[i] - fee)
        #hold[i] = max(hold[i - 1], cash - price[i])
        #cash[0] = 0
        #hold[i] = -price[0]
        n = len(prices)
        dp = [[0, -prices[0]]] + [[0, 0] for _ in range(n - 1)]
        for i in range(1, n):
            dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i] - fee)
            dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - prices[i])
        return dp[n - 1][0]