Best Time to Buy and Sell Stock IV
Real-world version: Season Flip LimitThe statement here is our own: the same inputs, outputs and technique.
A reseller works a season of len(quotes) trading days, and quotes[i] is the price a
single collectible fetches on day i.
The reseller holds at most one copy at a time. Buying is only allowed with nothing in hand,
and selling is only allowed with a copy in hand, so a purchase must be closed by a sale
before the next purchase. A buy paired with its sale counts as one flip, and the season
allows at most flips of them. Buying and selling on the same day is permitted. Doing
nothing on a day is always allowed, and a copy still in hand at the end of the season is
simply kept, contributing nothing.
Return the largest total gain the season can produce, where a flip contributes the sale price minus the purchase price. A season with no worthwhile flip returns 0.
Examples
Example 1
- Input
- flips = 1, quotes = [1,4,2,5]
- Output
- 4
Buy on day 0 at 1 and sell on day 3 at 5. That is one flip and a gain of 4.
Example 2
- Input
- flips = 2, quotes = [3,8,2,9,1,7]
- Output
- 13
Buy on day 2 at 2 and sell on day 3 at 9 for 7, then buy on day 4 at 1 and sell on day 5 at 7 for 6. Two flips, 13 in total.
Constraints
- 1 <= flips <= 100
- 1 <= quotes.length <= 1000
- 0 <= quotes[i] <= 1000
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.
def best_flip_total(flips: int, quotes: list[int]) -> int:public int bestFlipTotal(int flips, int[] quotes)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 10 test cases: 10 passed
- Passed: 2 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's