惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 叶小钗
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Security Blog
Microsoft Security Blog
罗磊的独立博客
大猫的无限游戏
大猫的无限游戏
美团技术团队
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
aimingoo的专栏
aimingoo的专栏
腾讯CDC
WordPress大学
WordPress大学
Apple Machine Learning Research
Apple Machine Learning Research
F
Fortinet All Blogs
G
Google Developers Blog
MongoDB | Blog
MongoDB | Blog
Microsoft Azure Blog
Microsoft Azure Blog
小众软件
小众软件
Engineering at Meta
Engineering at Meta
博客园_首页
B
Blog RSS Feed
D
Docker
M
MIT News - Artificial intelligence
爱范儿
爱范儿
I
InfoQ

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Sliding Window Maximum | Monotonic Deque
Jaspreet singh · 2026-06-28 · via DEV Community

Jaspreet singh

Problem Statement

Given an array nums and an integer k, return the maximum element for every sliding window of size k.


Brute Force Intuition

In an interview, you can explain it like this:

For every window of size k, iterate through all its elements and find the maximum.

Since every window is scanned completely, many elements are processed repeatedly.

Complexity

  • Time Complexity: O(N × K)
  • Space Complexity: O(1)

Brute Force Code

class Solution {

    public int[] maxSlidingWindow(int[] nums, int k) {

        int n = nums.length;

        int[] ans = new int[n - k + 1];

        int index = 0;

        for (int i = 0; i <= n - k; i++) {

            int max = nums[i];

            for (int j = i; j < i + k; j++) {

                max = Math.max(max, nums[j]);
            }

            ans[index++] = max;
        }

        return ans;
    }
}


Moving Towards the Optimal Approach

Notice that while moving the window:

One element leaves

One element enters

Do we really need to calculate the maximum again?

No.

We only need to keep the useful candidates that can become the maximum.

This is where a Monotonic Deque comes in.


Pattern Recognition

Whenever you see:

  • Sliding Window
  • Maximum / Minimum in every window
  • Fixed Window Size

Think:

Monotonic Deque


Key Observation

Maintain indices in a deque such that:

Elements remain in decreasing order.

Then:

Front of deque

=

Maximum of current window

Whenever a new element comes:

Remove all smaller elements from the back.

They can never become the maximum.


Optimal Approach

For every index:

Step 1

Remove indices outside the window.

deque.peekFirst() <= i - k


Step 2

Remove smaller elements from the back.

nums[deque.peekLast()] <= nums[i]


Step 3

Insert current index.


Step 4

Once window size becomes k:

Front of deque
=
Maximum


Optimal Java Solution

class Solution {

    public int[] maxSlidingWindow(int[] nums, int k) {

        int n = nums.length;

        int[] ans = new int[n - k + 1];

        Deque<Integer> dq = new ArrayDeque<>();

        int index = 0;

        for (int i = 0; i < n; i++) {

            while (!dq.isEmpty() &&
                   dq.peekFirst() <= i - k) {

                dq.pollFirst();
            }

            while (!dq.isEmpty() &&
                   nums[dq.peekLast()] <= nums[i]) {

                dq.pollLast();
            }

            dq.offerLast(i);

            if (i >= k - 1) {

                ans[index++] = nums[dq.peekFirst()];
            }
        }

        return ans;
    }
}


Dry Run

Input

nums = [1,3,-1,-3,5,3,6,7]

k = 3


Window

[1 3 -1]

Deque:

3

Maximum:

3


Window

[3 -1 -3]

Maximum:

3


Window

[-1 -3 5]

Remove:

-3

-1

Deque:

5

Maximum:

5

Continue similarly.

Final Answer:

[3,3,5,5,6,7]


Why Monotonic Deque Works?

Every index:

Inserted once

Removed once

So each element is processed only one time.

The deque always maintains candidates in decreasing order.

The front always stores the maximum element of the current window.


Complexity Analysis

Metric Complexity
Time Complexity O(N)
Space Complexity O(K)

Interview One-Liner

Maintain a monotonic decreasing deque of indices so the front always represents the maximum element of the current sliding window.


Pattern Learned

Sliding Window

+

Maximum / Minimum

↓

Monotonic Deque

Similar Problems

  • Sliding Window Maximum
  • Sliding Window Minimum
  • First Negative Integer in Every Window
  • Shortest Subarray with Sum at Least K
  • Constrained Subsequence Sum

Memory Trick

Think:

New Element Arrives

↓

Remove Smaller Elements

↓

Insert Current Index

↓

Front = Maximum

Mental Model

Sliding Window

↓

Useful Candidates Only

↓

Deque

↓

Front Always Maximum

Whenever you hear:

"Maximum in every sliding window"

your brain should immediately think:

Monotonic Deque