</>

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

Medium
1-D Dynamic Programming Time O(n) Space O(n)
↗ Open on LeetCode Source: Misc

Quick review

Pattern
1-D Dynamic Programming
Time
O(n)
Space
O(n)

Standard Solution (C++)

SummaryGiven a list of daily stock prices and a flat per-transaction fee, find the maximum profit achievable by making as many buy/sell transactions as desired, where each completed transaction (buy + sell) incurs the fee once.

Approach
  • Model each day with two states: hold (max cash while holding a share) and free (max cash while holding no share).
  • Transitions: hold = max(hold, free - price) (buy or do nothing); free = max(free, hold + price - fee) (sell paying the fee, or do nothing).
  • Because each state depends only on the previous day's values, we can maintain just two scalar variables instead of full arrays, giving O(1) space.
  • The answer is free at the end of the array — we never want to be left holding a share.
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    int maxProfit(vector<int>& prices, int fee) {
        // hold: best cash balance when we are currently holding a stock
        // free: best cash balance when we hold no stock
        int hold = -prices[0];
        int free = 0;

        for (int i = 1; i < (int)prices.size(); ++i) {
            int prevHold = hold;
            // Either buy today (pay prices[i]) or keep holding
            hold = max(hold, free - prices[i]);
            // Either sell today (collect prices[i], pay fee) or stay flat
            free = max(free, prevHold + prices[i] - fee);
        }

        return free;
    }
};
Time O(n) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    int maxProfit(vector<int>& prices, int fee) {
        int numOfDays=prices.size();
        vector<int> hold(numOfDays, 0);
        vector<int> notHold(numOfDays, 0);

        hold[0]=-prices[0];
        notHold[0]=0;

        for(int i=1; i<numOfDays; i++){
            hold[i]=max(hold[i-1], notHold[i-1]-prices[i]);
            notHold[i]=max(notHold[i-1], hold[i-1]+prices[i]-fee);
        }

        return notHold[numOfDays-1];
    }
};

// Time Complexity: O(n)
// Space Complexity: O(n), could be optimized to O(1)
Time O(n) Space O(n)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern