Show problems as
Classic problem #714MediumArrayDynamic ProgrammingGreedy

Best Time to Buy and Sell Stock with Transaction Fee

Real-world version: Handling Fee Resale
Tracked in this browser only
Read Best Time to Buy and Sell Stock with Transaction Fee on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A scrap yard trades a single bale of copper at a time. quotes[i] is the price the bale fetches on day i, and every completed sale is charged a flat handling fee of commission.

The yard may trade as often as it likes but never holds two bales: a purchase is only allowed with the yard clear, and a sale is only allowed with a bale on the ground. Buying and selling on the same day is permitted. The handling fee is charged once per sale, never on a purchase. A bale still on the ground when the days run out is simply left there and earns nothing.

Return the largest net cash position the yard can finish with, counting each sale as its price minus the purchase price minus the handling fee. Trading nothing at all leaves 0.

Examples

Example 1

Input
quotes = [4,7,5,11,6,12], commission = 3
Output
7

Buy at 4 and sell at 11, then buy at 6 and sell at 12. The two sales bring in 7 and 6 before fees, and the two fees of 3 leave 7.

Example 2

Input
quotes = [1,4,3,6], commission = 2
Output
3

Buy at 1 on day 0 and sell at 6 on day 3. That is 5 before the fee and 3 after the single fee of 2.

Constraints

  • 1 <= quotes.length <= 5 * 10^4
  • 1 <= quotes[i] < 5 * 10^4
  • 0 <= commission < 5 * 10^4

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def net_resale_gain(quotes: list[int], commission: int) -> int:
Java
public int netResaleGain(int[] quotes, int commission)