Skip to content
Decoder

Best Time to Buy and Sell Stock with Transaction Fee

Medium

Problem

prices[i] is a stock's price on day i, and every completed trade (a buy followed by a sell) costs a flat `fee`. You may make as many transactions as you like, but you can hold at most one share at a time. Return the maximum profit.

Example 1

Input
prices = [1, 3, 2, 8, 4, 9], fee = 2
Output
8
Why
buy 1, sell 8, buy 4, sell 9

Example 2

Input
prices = [1, 3, 7, 5, 10, 3], fee = 3
Output
6

Constraints

  • 1 <= prices.length <= 5 * 10^4
  • 1 <= prices[i] < 5 * 10^4
  • 0 <= fee < 5 * 10^4

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.