Skip to main content
Back to problems
Leetcode
Medium
Arrays
Queues
Heaps
Google
Meta
Amazon
Sliding Window Maximum

Find the maximum element in every contiguous subarray of size kk.

Acceptance 63%
Problem Statement

Given an integer array nums and an integer k, consider every contiguous subarray of length k. For each window, return the largest value contained in that window.

Your task is to produce the sequence of window maximums in the same order the windows appear from left to right.

Input Format

  • An integer array nums
  • An integer k representing the window size

Output Format

  • Return an array where the ii-th element is the maximum of nums[i .. i+k-1]

Constraints

  • 1knums1 \le k \le |nums|
  • The array may contain duplicate values and negative values
  • Aim for an efficient solution better than checking every window element-by-element
Examples
Sample cases returned by the problem API.

Example 1

Input

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

Output

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

Explanation

The windows are [1,3,-1], [3,-1,-3], [-1,-3,5], [-3,5,3], [5,3,6], and [3,6,7]. Their maximums are 3, 3, 5, 5, 6, and 7.

Example 2

Input

nums = [4,2,12,11,-5], k = 2

Output

[4,12,12,11]

Explanation

The windows are [4,2], [2,12], [12,11], and [11,-5]. Their maximums are 4, 12, 12, and 11.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.