LeetCode Pattern/Sliding Window/Why Sliding Window Doesn’t Work on LeetCode Stock Problems

Why Sliding Window Doesn’t Work on LeetCode Stock Problems

LeetCopilot Team
Nov 20, 2025
6 min read
Stock ProblemsDynamic ProgrammingGreedyAnti-Pattern
Best Time to Buy and Sell Stock looks like a window problem. But trying to use Sliding Window will lead you down a rabbit hole. Learn why DP or Greedy is the real answer.

LeetCode 121: "Best Time to Buy and Sell Stock".
It asks for a time range (buy day, sell day).
It asks for a maximum profit.
It sounds like a Sliding Window.

But if you try to implement a standard while(invalid) shrink loop, you will get confused. Why? Because Stock problems are not about a "valid window condition"—they are about state transitions.

TL;DR — Stock Problem Cheat Sheet

  • Is it Sliding Window? No.
  • Is it Contiguous? No, transactions are discrete points.
  • The Pattern: It's usually Greedy (finding local/global min-max) or DP (making a sequence of decisions).
  • The Trap: Trying to "shrink" the window. You don't shrink; you just wait for a better price.

What are “stock problems”?

These problems usually involve an array of prices prices[i] and rules about transactions:

  • Buy once, sell once.
  • Buy and sell unlimited times.
  • At most K transactions.
  • Cooldown periods.

Why sliding window pattern mis-applies here

1. Profit is not Monotonic

In a standard window, adding an element usually increases the "sum" or "count".
In stocks, adding a price might decrease your profit if the price crashes.

2. Transactions are Split

A "transaction" isn't a contiguous subarray of prices. It's just two points: prices[buy] and prices[sell]. What happens in between doesn't matter for the profit calculation (unlike a sum).

Better patterns

1. Greedy (One Pass)

For "Buy Once":

  • Track minPrice so far.
  • Calculate profit = price - minPrice.
  • Update maxProfit.
  • This looks like a window (left=minPrice index, right=current), but we never "shrink" incrementally. We just jump left to right if we find a new low.

2. Dynamic Programming (State Machine)

For "Unlimited" or "K transactions":

  • States: Held, Sold, Cooldown.
  • Transitions: Held[i] = max(Held[i-1], Sold[i-1] - prices[i]).

Code walkthrough: Stock Problem Failure

Attempting Sliding Window:

// Confusing Sliding Window attempt
let left = 0;
for (let right = 1; right < prices.length; right++) {
    if (prices[right] < prices[left]) {
        left = right; // Hard reset, not a shrink
    }
    // ... logic gets messy for multiple transactions
}
typescript

Correct Greedy Approach:

let minPrice = Infinity;
let maxProfit = 0;
for (let price of prices) {
    if (price < minPrice) {
        minPrice = price; // Just update reference
    } else {
        maxProfit = Math.max(maxProfit, price - minPrice);
    }
}
typescript

Checklist: When you see “stock”

KeywordPattern
"Buy and Sell Once"Greedy (Track Min)
"Unlimited Transactions"Greedy (Sum positive slopes)
"K Transactions"Dynamic Programming (3D Array)
"Cooldown / Fee"Dynamic Programming (State Machine)

Summary

Don't force Sliding Window on Stock problems.

  • They are Temporal (Time matters), but not Contiguous Accumulations.
  • Use Greedy for simple cases.
  • Use DP for complex constraints.

Next Step:
You have now explored the boundaries of Sliding Window. Return to the Pattern Hub to master the next technique.

Struggling with the DP part? Learn how to visualize it in Visualizing the Unseen: Recursion and DP.

Ready to Practice This Pattern?

Apply this pattern with LeetCopilot's AI-powered hints, notes, and mock interviews. Transform your coding interview preparation today.

Related Tutorials