36 · DP Patterns

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

Mediumsolve on LeetCode ↗

frequently reported atBloombergGoogleMicrosoftAmazon

the problem

In plain words

prices[i] is a stock's price on day i, and every completed trade (one buy plus the sell that closes it) costs a fixed fee. You may trade any number of times but hold at most one share at a time. Return the largest total profit after paying all fees.

in prices = [1,3,2,8,4,9], fee = 2

out 8

Buy at 1, sell at 8 (7 − 2 = 5); buy at 4, sell at 9 (5 − 2 = 3).

in prices = [1,3,7,5,10,3], fee = 3

out 6

  • 1 ≤ prices.length ≤ 5·10⁴
  • 1 ≤ prices[i] < 5·10⁴
  • 0 ≤ fee < 5·10⁴

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #309
    2. #122
      Best Time to Buy and Sell Stock II
      Mediumin Arrays & Strings