Algo-Sim › Dynamic Programming

Best Time to Buy and Sell Stock with Transaction Fee

Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input

Trade as often as you like, paying a fee per trade. Two states per day, hold and free, with the fee on the sell arrow.

Problem

You are given prices, where prices[i] is the price of a stock on day i, and a fee paid on every completed transaction. You may buy and sell as many times as you like, but hold at most one share at a time. Return the maximum profit.

Constraints

Edge cases to test

Follow-up questions

Does it matter where the fee is paid?
No: on the buy or on the sell gives the same answer, as long as it is paid once per trade.
Why not just sum the rises above the fee?
Holding through a small dip can avoid paying the fee twice; the two-state DP decides that.

Solution

Java

public int maxProfit(int[] prices, int fee) {
    int n = prices.length;
    int[] hold = new int[n], free = new int[n];
    hold[0] = -prices[0];
    for (int i = 1; i < n; i++) {
        hold[i] = Math.max(hold[i - 1], free[i - 1] - prices[i]);
        free[i] = Math.max(free[i - 1], hold[i - 1] + prices[i] - fee);
    }
    return free[n - 1];
}

Python

def max_profit(prices, fee):
    n = len(prices)
    hold, free = [0] * n, [0] * n
    hold[0] = -prices[0]
    for i in range(1, n):
        hold[i] = max(hold[i - 1], free[i - 1] - prices[i])
        free[i] = max(free[i - 1], hold[i - 1] + prices[i] - fee)
    return free[n - 1]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int maxProfit(vector<int> &prices, int fee) {
        int n = int(prices.size());
        vector<int> hold(n), free(n);
        hold[0] = -prices[0];
        for (int i = 1; i < n; i++) {
            hold[i] = max(hold[i - 1], free[i - 1] - prices[i]);
            free[i] = max(free[i - 1], hold[i - 1] + prices[i] - fee);
        }
        return free[n - 1];
    }
};

More Dynamic Programming problems