KatInterview

Best Single Trade Within a Limited Holding Period

Arrays & HashingModel answer
MediumModel answerArrays & Hashingsliding-windowblock-decompositionmonotonic-deque

Last 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 space O(1).
  • Handle n < 2, non-increasing prices, D = 1, and D ≥ n.

Example. prices = [3, 1, 4, 1, 5], D = 2 gives profit 4 with (i, j) = (3, 4).

Discussion points. Explain:

  1. Why the usual sliding-window-minimum approach misses the space requirement.
  2. How your design changes if prices arrive as a stream.
  3. What happens when D is 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.