712377. Buy Stock with Transaction Fee

Medium

Buy Stock with Transaction Fee

Summary

You are given an array prices representing stock prices over time, where each price is a non-negative integer. You can buy and sell stocks, but for each transaction, you need to pay a fee. Your goal is to maximize your profit by determining the optimal sequence of buy and sell transactions.

The problem involves arrays and algorithms, focusing on finding the maximum possible profit considering the transaction fee.

Detailed Explanation

To solve this problem, we will use dynamic programming to find the maximum profit. We will initialize an array dp with the same length as prices, where dp[i] represents the maximum profit that can be achieved by the end of day i.

Here's a step-by-step breakdown:

  1. Initialize max_profit = 0 and prev_min_price = prices[0].
  2. Iterate through the array prices:
    • For each day i, calculate the profit profit = prices[i] - prev_min_price. If this is positive, add the fee to the profit (profit -= fee).
    • Update max_profit if the current profit is greater.
    • Update prev_min_price as the minimum price seen so far.
  3. Return max_profit as the maximum possible profit.

Time complexity: O(n), where n is the length of the array prices. Space complexity: O(1), since we only use a constant amount of space to store the variables.

Optimized Solutions

Java

View on GeeksforGeeks
public int maxProfit(int[] prices, int fee) {
    int max_profit = 0;
    int prev_min_price = prices[0];
    for (int i = 1; i < prices.length; i++) {
        int profit = prices[i] - prev_min_price;
        if (profit > 0) {
            profit -= fee;
        }
        max_profit = Math.max(max_profit, profit);
        prev_min_price = Math.min(prev_min_price, prices[i]);
    }
    return max_profit;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.