Best time to buy and sell stock with transaction fees

Dynamic Programming DP on stocks Medium

Given an array arr where arr[i] represents the price of a given stock on the ith day. Additionally, you are given an integer fee representing a transaction fee for each trade. The task is to determine the maximum profit you can achieve such that you need to pay a transaction fee for each buy and sell transaction. The Transaction Fee is applied when you sell a stock.

You may complete as many transactions. You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before buying again).

Examples:

Input: arr = [1, 3, 4, 0, 2], fee = 1

Output: 3

Explanation: Buy at day 1, sell at day 3, then, buy at day 4, sell at day 5.

Profit calculation: ((4 - 1) - 1) + ((2 - 0) - 1) = 2 + 1 = 3.

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

Output: 8

Explanation: Buy at day 1 (price = 1), sell at day 4 (price = 8), then Buy at day 5 (price = 4), sell at day 6 (price = 9),

Profit calculation: ((9 - 4) - 2) + ((8 - 1) - 2)= 8.

Input: arr = [10, 3, 7, 5, 1, 3], fee = 3

Constraints

  • 1 <= n<= 105
  • 0 <= arr[i] ,fee<= 104

Hints

  • "We use DP to track two states: hold → Maximum profit when holding a stock. not_hold → Maximum profit when not holding a stock."
  • If we hold a stock on day i, we either Keep holding it or Buy it today. If we do not hold a stock on day i, we either Keep not holding or Sell it today and pay the transaction fee

Company Tags

Medtronic HashiCorp Alibaba Seagate Technology Broadcom Shopify Ernst & Young Target Pinterest Red Hat Robinhood Bungie Cloudflare NVIDIA Siemens Healthineers OYO Rooms Oracle Square Morgan Stanley Zynga Epic Systems eBay MongoDB Flipkart Micron Technology Google Microsoft Amazon Meta Apple Netflix Adobe