Skip to content
LeetQuant
F7 Programming and Algorithms Foundations

F7 · Programming and Algorithms Foundations · Lesson 1 of 6

Single-Pass Algorithms on Price Series

Running state, Kadane's algorithm, prefix sums and monotonic deques: O(n) solutions to the most common coding questions.

25 min

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 O(n2)O(n^2). The O(n)O(n) 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 [2,−3,4,−1,2,−5,3][2, -3, 4, -1, 2, -5, 3]. What is the best contiguous stretch?

Show solution

The run ending at each position has sum 2,−1,4,3,5,0,32, -1, 4, 3, 5, 0, 3 (at position 3 the algorithm restarts, since 4>−1+44 > -1 + 4). The best is 55, from the stretch [4,−1,2][4, -1, 2].

Prefix sums

Precompute P0=0P_0 = 0 and Pi+1=Pi+xiP_{i+1} = P_i + x_i. Then any range sum is a difference:

xi+xi+1+⋯+xj−1=Pj−Pi,x_i + x_{i+1} + \dots + x_{j-1} = P_j - P_i ,

so rolling means, range queries and "is there a window with sum kk?" questions become O(1)O(1) each after O(n)O(n) 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 ww looks like it needs O(nw)O(nw) work. A monotonic deque does it in O(n)O(n): 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 PP where P0=0P_0 = 0 and Pi+1=Pi+xiP_{i+1} = P_i + x_i, which expression equals x3+x4+x5x_3 + x_4 + x_5?

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).