Best Single Trade Within a Limited Holding Period
Arrays & HashingModel answerLast updated
Find the most profitable buy-then-sell pair in a price array when the sale must happen within D days of the purchase, in O(n) time and O(1) extra space.
You are given an array prices of length n, where prices[k] is an asset's price on day k, and an integer D ≥ 1. You may make at most one trade: buy on day i, then sell on day j, where
i < j ≤ min(i + D, n - 1)
In other words, you must sell at least one day after buying, but no more than D days after.
Task. Return the largest achievable profit prices[j] - prices[i] together with the pair (i, j) that achieves it. If no trade gives a strictly positive profit, return 0 and indicate that no trade should be made (for example (0, None)).
Requirements
- Time
O(n)and extra spaceO(1). - Handle
n < 2, non-increasing prices,D = 1, andD ≥ n.
Example. prices = [3, 1, 4, 1, 5], D = 2 gives profit 4 with (i, j) = (3, 4).
Discussion points. Explain:
- Why the usual sliding-window-minimum approach misses the space requirement.
- How your design changes if prices arrive as a stream.
- What happens when
Dis extremely large.
Hints
Hint 1
A monotonic deque gives the window minimum in O(n) time, but it can hold up to D entries. To get O(1) space, find a structure that avoids storing the window.
Hint 2
Cut the array into consecutive blocks of length D. Any valid pair lies either inside one block or in two neighbouring blocks. Handle each case with a running value.
Hint 3
For a buy at offset a in one block and a sell at offset c in the next block, the gap is D + c - a. The limit gap ≤ D becomes c ≤ a, so the best sell for buy offset a is the prefix maximum of the next block up to offset a.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Problem in one line
Maximize prices[j] - prices[i] over pairs with 1 ≤ j - i ≤ D. Report (0, None) if the maximum is not strictly positive.
Baseline and why it falls short
For each sell day j, we need the minimum price over [j-D, j-1]. A monotonic deque (indices with increasing prices, expiring from the front) gives this in amortized O(1) per day, so the total is O(n) time. But the deque can hold up to min(D, n) entries, for example on a strictly increasing array. That is O(D) space, not O(1).
O(1)-space idea: aligned blocks
First clamp D = min(D, n - 1), since a longer window changes nothing. Split the indices into blocks of length D: [0, D), [D, 2D), and so on, with the last block possibly shorter.
For a valid pair, j - i ≤ D, so i and j are in the same block or in adjacent blocks. Each case needs only a running value.
Case 1: same block. Two indices in one block differ by at most D - 1, so the window limit is automatically satisfied. Run the classic one-trade scan inside each block: track the index of the smallest price seen so far in the block and test each j against it.
Case 2: adjacent blocks. Let the earlier block start at p and the later one at s = p + D. Write i = p + a and j = s + c with offsets a, c ∈ [0, D). Then
j - i = D + c - a
j - i ≤ Dis equivalent toc ≤ a.j - i ≥ 1always holds, becausea ≤ D - 1.
So for a buy at offset a, the allowed sells are exactly offsets 0..a of the later block. Sweep a from 0 to D - 1 and keep a running maximum (by index) over the later block's first a + 1 elements. At each step, compare that maximum with prices[p + a]. If s + a ≥ n, the later block has ended, so the running maximum stays as it is. It still covers every existing offset c ≤ a.
The answer is the best result over both cases.
Why it is correct
- Complete. Every valid pair is either in the same block (covered by Case 1, since the running minimum includes
ior something at least as cheap) or in adjacent blocks withc ≤ a(covered by Case 2, since the running maximum at stepaincludesc). - Sound. Case 1 only examines pairs with gap in
[1, D-1]. Case 2 only examines pairs with gap in[1, D]. Nothing outside the window is ever considered.
Code (Python)
from typing import List, Optional, Tuple
def best_trade(prices: List[float], D: int) -> Tuple[float, Optional[Tuple[int, int]]]:
if D < 1:
raise ValueError("D must be at least 1")
n = len(prices)
if n < 2:
return 0, None
D = min(D, n - 1)
best, pair = 0, None
# Case 1: both days in the same block.
for start in range(0, n, D):
end = min(start + D, n)
lo = start
for j in range(start + 1, end):
if prices[j] - prices[lo] > best:
best, pair = prices[j] - prices[lo], (lo, j)
if prices[j] < prices[lo]:
lo = j
# Case 2: buy in the block before s, sell in the block starting at s,
# with sell offset <= buy offset.
for s in range(D, n, D):
p = s - D
hi = s
for a in range(D):
j = s + a
if j < n and prices[j] > prices[hi]:
hi = j
i = p + a
if prices[hi] - prices[i] > best:
best, pair = prices[hi] - prices[i], (i, hi)
return (best, pair) if pair else (0, None)
Trace. prices = [3, 1, 4, 1, 5], D = 2. Blocks are [0,1], [2,3], [4].
- Same-block pairs
(0,1)and(2,3)lose money. - Block pair starting at
s = 2: best is buy day 1, sell day 2, profit 3. - Block pair starting at
s = 4: buy day 3, sell day 4, profit 4. - Result:
(4, (3, 4)).
Complexity
- Time O(n). Case 1 touches each index once. Case 2 touches each index at most twice, once as a buy and once as a sell.
- Space O(1). A handful of indices and the best result.
Edge cases
n < 2: return(0, None).- Non-increasing or constant prices: no strictly positive profit, so
(0, None). D = 1: blocks have size 1, Case 1 does nothing, and Case 2 checks exactly the consecutive pairs.D ≥ n: clamping ton - 1leaves one full block and a tail of length 1, which behaves like the unbounded "buy low, sell high" scan.- Ties: the code keeps the first pair found. If a specific tie-break is required (earliest buy, earliest sell), confirm it up front and adjust the comparisons.
Follow-up: streaming input
The block approach re-reads the previous block, so it needs random access. On a true one-pass stream, there is an information-theoretic obstacle: any of the last D prices might later become the best buy, depending on what arrives next. So Θ(D) memory is unavoidable in the worst case if you want exact answers.
The practical design is the monotonic deque:
- On each new price at day
t, drop front entries with index< t - D. - The front is the cheapest eligible buy, so the candidate profit is
price_t - front.price. Update the running best(profit, i, j). - Pop back entries with price
≥ price_t, then append dayt.
This is O(1) amortized per tick, and the deque holds only strictly increasing prices, which is often far fewer than D on real data. If memory is capped, you can store one minimum per bucket of B days (O(D/B) memory), but then the answer is approximate unless sells are restricted to bucket boundaries. State this as a trade-off.
Follow-up: very large D
- Offline. Clamp
Dton - 1. No other change is needed, and the work stays linear. - Streaming. Until day
Dis reached, nothing expires, so the front of the deque is just the running minimum, and a single variable is enough. Expiry (and thus the deque) matters only once the stream is longer thanD. IfDis larger than any stream you expect, the problem reduces to the classic unbounded trade. Otherwise accept O(D) worst-case memory or use the bucketed approximation.
Common mistakes
- Using a deque and claiming O(1) space.
- Forgetting to clamp
D, or mishandling a short final block. - Letting the cross-block sweep allow
c > a, which produces gaps larger thanD. - Returning a zero-profit pair instead of "no trade".