← Questions

Best time to buy and sell stock with a limited holding window

0
MicrosoftCodingLast asked Aug 2025

A coding interview question asked in Microsoft's coding round, last asked Aug 2025. It tests arrays, sliding window and greedy.

You get daily stock prices prices[0..n-1] and an integer D >= 1. Make at most one transaction: buy on day i and sell on a later day j, where the sale must happen within D days of the purchase (i < j <= i + D). Return the best profit and the days that achieve it. If no transaction makes a strictly positive profit, return no transaction.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • max_profit_window(prices: list[int], D: int) -> list[int] — returns [profit, i, j], or [0, -1, -1] when no positive profit exists. Any optimal pair is accepted on ties.

Example

prices = [3, 2, 6, 5, 0, 3], D = 2   ->  [4, 1, 2]     # buy at 2, sell at 6
prices = [7, 6, 4, 3, 1],    D = 3   ->  [0, -1, -1]   # prices only fall
prices = [1, 2, 100],        D = 1   ->  [98, 1, 2]    # buying on day 0 to sell on day 2 is too long
prices = [1, 2, 100],        D = 2   ->  [99, 0, 2]

Constraints

  • 0 <= n <= 10^5; with n < 2 no transaction is possible.
  • Prices are integers and may be zero or negative.
  • Aim for O(n) time.

Clarifying questions

  • Is the window j - i <= D, inclusive?
  • Must I return the days, or only the profit?
  • What should I return when no positive profit exists?

What a strong answer covers

  • Why the classic running-minimum solution is wrong here: it can buy arbitrarily far in the past.
  • Fixing the sell day j, the best buy is the minimum price in [j - D, j - 1]: a sliding-window minimum.
  • A monotonic deque of indices with increasing prices: drop indices that left the window, score selling at j against the front, then push j after popping larger or equal prices. O(n) time, O(D) space.
  • The order of operations (score before pushing j), and tests for D = 1, D >= n and all-falling prices.

Follow-ups

  • Prices arrive as a stream: what state do you keep, and what does it cost per tick?
  • D is huge. What does the deque degenerate to?
  • Allow up to two transactions, each within the window.

Where it's asked

  • Microsoft · Coding · Last asked Aug 202560 min · Ten to fifteen minutes of behavioral questions, then coding in HackerRank where you write a main and make the tests pass; usually three rounds · No AI unless the interviewer invites it; some 2026 loops add a round where you bring your own AI agent

What it tests

arrays · sliding window · greedy

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding