Maximize profit with bounded sell window
Company: Microsoft
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates proficiency in array algorithms, time and space complexity analysis, and techniques for bounded-range optimization and streaming adaptation.
Constraints
- 1 <= D (the sell day j must satisfy i < j <= min(i + D, n - 1)).
- 0 <= n; n may be 0 or 1, in which case no transaction is possible -> [0, -1, -1].
- Prices may be zero or negative (e.g. spread/relative values); profit is prices[j] - prices[i].
- At most one transaction (one buy followed by one later sell).
- Only strictly positive profit counts; ties on profit may return any optimal (i, j).
Examples
Input: ([3, 2, 6, 5, 0, 3], 2)
Expected Output: [4, 1, 2]
Explanation: Buy at index 1 (price 2), sell at index 2 (price 6) within the 2-day window; profit 4.
Input: ([7, 6, 4, 3, 1], 3)
Expected Output: [0, -1, -1]
Explanation: Prices are strictly decreasing, so no buy/sell pair gives positive profit -> no transaction.
Hints
- Fix the sell day j and ask: what is the cheapest buy day i allowed? It must lie in the sliding window [max(0, j - D), j - 1]. So this is a sliding-window-minimum problem, not the classic O(n) running-min trick (which would let you buy arbitrarily far in the past).
- Maintain a monotonic deque of indices whose prices are increasing. The front is always the index of the minimum price in the current window. Before scoring day j, pop front indices that have fallen out of [j - D, j - 1].
- Order matters: evaluate selling at j against the deque front FIRST (the front holds buy days strictly before j), THEN push j itself as a candidate buy day for the next D sell days. For streaming input, you only ever keep the last D prices' worth of deque entries, and for very large D the deque simply stops being a binding constraint (it degenerates to the standard track-the-running-minimum solution).