Last active
September 15, 2019 20:45
-
-
Save santhalakshminarayana/0b700b9ff807a258b5e96d8aa7176599 to your computer and use it in GitHub Desktop.
Given an array of integers and a number k, where 1 <= k <= length of the array, compute the maximum values of each subarray of length k.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
For example, given array = [10, 5, 2, 7, 8, 7] and k = 3, we should get: [10, 7, 8, 8], since: | |
10 = max(10, 5, 2) | |
7 = max(5, 2, 7) | |
8 = max(2, 7, 8) | |
8 = max(7, 8, 7) | |
''' | |
from collections import deque | |
def largest_subarray(arr,n,k): | |
''' | |
arr(list):list of array elements | |
n(int):size of array | |
k(int):subarray size | |
''' | |
dq=deque() | |
for i in range(k): | |
while dq and arr[i] >= arr[dq[-1]] : | |
dq.pop() | |
dq.append(i); | |
for i in range(k,n): | |
print(arr[dq[0]]) | |
while dq and dq[0] <= i-k: | |
dq.popleft() | |
while dq and arr[i] >= arr[dq[-1]] : | |
dq.pop() | |
dq.append(i) | |
print(arr[dq[0]]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment