cconnected.
Understand the pattern. Find your own way.Find your starting point
Your learning feed/Idea 137 of 218
Ideas this builds on
Advanced DP patterns137 / 218

Monotonic queue optimizes a DP window

Picture

Suppose dp[i] needs the maximum dp among the previous k positions. Scanning all k repeats comparisons.

Predict

Why can a smaller older candidate be removed?

Walk through the small example

It expires earlier and never beats the newer larger value. Candidates have ordered expiry and dominance, allowing a deque to keep only possible future winners.

Mental model and complete Python solution

Each previous state is a job applicant with a score and expiry time. A newer, better applicant dominates an older worse one. The front is today’s winner.

What the function promises: Return the maximum score reaching the final index when jumps may advance 1..k and landing adds values[i]. Require nonempty values and positive k.

from collections import deque

def max_jump_score(values, k):
    if not values or k <= 0: raise ValueError("Invalid input")
    dp = [0] * len(values)
    dp[0] = values[0]
    useful = deque([0])
    for i in range(1, len(values)):
        while useful[0] < i-k: useful.popleft()
        dp[i] = values[i] + dp[useful[0]]
        while useful and dp[useful[-1]] <= dp[i]: useful.pop()
        useful.append(i)
    return dp[-1]

assert max_jump_score([1,-1,-2,4,-7,3], 2) == 7
assert max_jump_score([10], 3) == 10

Work and storage: O(n) time and O(n) DP storage here; the deque is O(k). DP storage can also be bounded when reconstruction is unnecessary.

When to recognize it: Candidates have ordered expiry and dominance, allowing a deque to keep only possible future winners.

Check before applying it: The recurrence must truly depend on a contiguous index window; arbitrary predecessor sets need another structure.

Change one rule

Transition adds a predecessor-specific edge cost.

See what changes

A simple maximum of dp[j] no longer captures the transition; find a transform or use a suitable range structure.

Connect

one dimensional: Keep the same recurrence while accelerating its transition.

monotonic stack: Both remove dominated candidates; the deque also expires from the front.