Carry the right state
Many interview questions on time series ask for a maximum or minimum over all pairs or windows. The brute force is . The solution almost always scans once and keeps a small amount of running state: the best value so far, the lowest price so far, the current partial sum.
The design question is always: what do I need to remember about the past to answer the question at the current step? Say this out loud before you code.
Kadane's algorithm
The best contiguous run of returns (the maximum subarray sum) keeps one number: the best sum of a run ending at the current position. Either extend the previous run or start fresh.
def max_subarray(xs: list[float]) -> float:
best = cur = xs[0]
for x in xs[1:]:
cur = max(x, cur + x) # extend the run or restart here
best = max(best, cur)
return best
The same "best ending here" idea solves the best single round trip (track the lowest price so far) and the maximum drawdown (track the highest price so far).
Worked example
tracing Kadane
Run Kadane's algorithm on daily PnL . What is the best contiguous stretch?
Show solutionHide solution
The run ending at each position has sum (at position 3 the algorithm restarts, since ). The best is , from the stretch .
Prefix sums
Precompute and . Then any range sum is a difference:
so rolling means, range queries and "is there a window with sum ?" questions become each after setup. Combined with a hash map of earlier prefix sums, you can count the windows summing to any target in one pass.
Sliding-window maximum
The maximum over every window of length looks like it needs work. A monotonic deque does it in : keep indices whose values are decreasing, drop indices that leave the window from the front, and before pushing a new value pop every smaller value from the back (they can never be the maximum again).
from collections import deque
def window_max(xs: list[float], w: int) -> list[float]:
dq, out = deque(), []
for i, x in enumerate(xs):
while dq and xs[dq[-1]] <= x:
dq.pop()
dq.append(i)
if dq[0] <= i - w:
dq.popleft()
if i >= w - 1:
out.append(xs[dq[0]])
return out
Each index is pushed and popped at most once, so the total work is linear.
Knowledge check
What does Kadane's algorithm return for [−2, 1, −3, 4, −1, 2, 1, −5, 4]?
Knowledge check
With prefix sums where and , which expression equals ?
Knowledge check
What is the total time complexity of the monotonic-deque sliding-window maximum over n elements with window w?
Practice problems
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).