Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Dynamic Programming

Stock Trading with a Transaction Fee

Medium · Dynamic Programming · Asked at Amazon, Meta, Bloomberg, Goldman Sachs

price[i] is a stock’s price on day i. You may complete as many transactions as you like (buy one share, then sell it before buying again), but every sale costs a fee f. Print the maximum total profit.

Input

First line: n f. Second line: the n prices.

Output

The maximum profit.

Constraints

Track two values per day: cash = best profit holding nothing, hold = best profit holding a share. cash = max(cash, hold + price − f); hold = max(hold, cash − price).

Example 1

Input

6 2
1 3 2 8 4 9

Output

8

Example 2

Input

6 3
1 3 7 5 10 3

Output

6

Hints

  1. On any day you either hold a share or you do not.
  2. Keep the best profit for both states.
  3. Selling moves you from "hold" to "cash" and costs the fee.

Approach

cash = best profit with no share, hold = best profit while holding one (initially −price[0]). Each day: cash = max(cash, hold + price − fee) and hold = max(hold, cash − price). Using the updated cash in the hold update is safe — it just models selling and rebuying on the same day, which never beats doing nothing. The answer is cash.

Complexity: O(n) time · O(1) space

Solution

C++ solution

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

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    long long fee;
    cin >> n >> fee;
    vector<long long> p(n);
    for (auto &x : p) cin >> x;
    long long cash = 0, hold = -p[0];
    for (long long x : p) {
        cash = max(cash, hold + x - fee);
        hold = max(hold, cash - x);
    }
    cout << cash << "\n";
    return 0;
}

Python solution

import sys

data = list(map(int, sys.stdin.read().split()))
n, fee = data[0], data[1]
p = data[2 : 2 + n]
cash, hold = 0, -p[0]
for x in p:
    cash = max(cash, hold + x - fee)
    hold = max(hold, cash - x)
print(cash)

Java solution

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int n = (int) in.nval;
        in.nextToken();
        long fee = (long) in.nval;
        long[] p = new long[n];
        for (int i = 0; i < n; i++) {
            in.nextToken();
            p[i] = (long) in.nval;
        }
        long cash = 0, hold = -p[0];
        for (long x : p) {
            cash = Math.max(cash, hold + x - fee);
            hold = Math.max(hold, cash - x);
        }
        System.out.println(cash);
    }
}

Solve Stock Trading with a Transaction Fee online · All practice problems