Show problems as
Classic problem #122MediumArrayDynamic ProgrammingGreedy

Best Time to Buy and Sell Stock II

Real-world version: Collectible Resale Run
Tracked in this browser only
Read Best Time to Buy and Sell Stock II on LeetCode(opens in a new tab)

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

A dealer trades one collectible and already knows what it will be quoted at on every trading day: quotes[i] is its price in whole credits on day i.

On each day the dealer may buy one copy, sell the copy currently held, or stand pat. Never more than one copy may be held at a time, so a copy has to be sold before another is bought, and a sale followed by a purchase on the same day is allowed. The dealer holds nothing before day 0 and must hold nothing once the last day closes.

Return the largest total profit available over the whole run.

Examples

Example 1

Input
quotes = [6, 1, 4, 2, 8, 5]
Output
9

Buy on day 1 at 1 and sell on day 2 at 4 for 3 credits, then buy on day 3 at 2 and sell on day 4 at 8 for 6 credits, totalling 9.

Example 2

Input
quotes = [8, 6, 4, 1]
Output
0

The quote never rises from one day to the next, so the dealer buys nothing and keeps a profit of 0.

Example 3

Input
quotes = [2, 2, 5, 5, 1, 1, 6]
Output
8

Hold from day 1 through day 3 for 3 credits, then from day 5 through day 6 for 5 credits; flat days add nothing either way.

Constraints

  • 1 <= quotes.length <= 3 * 10^4
  • 0 <= quotes[i] <= 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 resale_profit(quotes: list[int]) -> int:
Java
public int resaleProfit(int[] quotes)