codemistic / Data-Structures-and-Algorithms

A repository to help the open-source community with DSA related contributions
MIT License
322 stars 333 forks source link

Sliding Window Maximum #717

Closed ARYASINGHBJC closed 1 year ago

ARYASINGHBJC commented 1 year ago

class Solution: def maxSlidingWindow(nums, k): n = len(nums) dq = deque([]) ans = [] for i in range(n):

Eliminate elements less or equal to nums[i]

        while dq and nums[dq[-1]] <= nums[i]: dq.pop()  

        # Push index of current nums[i] to the deque
        dq.append(i)

        # if reach enough range size k -> add the result
        if i + 1 >= k: ans.append(nums[dq[0]])

        # Remove the last element of range size k
        if i - dq[0] + 1 >= k: dq.popleft()
    return ans