Categories
Computer Science

Solving Problem: Sliding Window Maximum

Arrays and Strings

Problem Statement:

You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.

Return the max sliding window.

Example 1:

Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation:
Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7

Example 2:

Input: nums = [1], k = 1
Output: [1]

Constraints:

  • 1 <= nums.length <= 105
  • -104 <= nums[i] <= 104
  • 1 <= k <= nums.length

Python:

class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
# Write your code here
max_array = []
for i in range(0, len(nums) - k + 1):
window_max = max(nums[i:i+k])
max_array.append(window_max)
return max_array
Priyanka B.'s avatar

By Priyanka B.

Hello and welcome to my little corner of internet!! I am a techie. I am very interested to discover and innovate new advances in science and technology. Blogging is one of my hobbies which I think is very useful for broadening my knowledge horizons and help me grow my skills. Apart from blogging I have also little taste in artistic skills and literature, which can keep my writing and posts tangy.

Whether you stumbled in by chance or came here on purpose, I hope you find something that sparks your curiosity or makes you think a little deeper. Thanks for stopping by!!

Leave a comment