Coding Problem 9
Maximum in Subarray
asked by Google
Ques. Given an array of integers and a number k, where 1<= k <= length of array, compute the maximum values of each subarray of length k. 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)
Solution.
This question has a simple solution. In array we will create a window which consist of number of elements equal to k and can find the maximum among them and append that in output list. But while traversing the array we have to keep something very important in mind. We will not traverse from index 0 to nth index. We will traverse upto (n-k)th index because when last k elements will come in the window after that we will not have enough k elements to keep them in the window. Lets see the code -
def maxFromSubarray(arr, n, k):
out = []
for i in range(0, n-k+1):
maxi = max(arr[i:i+k])
out.append(maxi)
return out
arr = [10, 5, 2, 7, 8, 7]
n = len(arr)
k = 3
res = maxFromSubarray(arr, n, k)
print(res)
Output: [10, 7, 8, 8]
Comments
Post a Comment