Q#56: Maximum of Subarrays

Given an array and an integer A, find the maximum for each contiguous subarray of size A.

Input: array = [1, 2, 3, 1, 4, 5, 2, 3, 6], A = 3
Output: 3 3 4 5 5 5 6

Below is a more detailed walkthrough of what you should be trying to code, using the example above:

  • subarray 1 = [1, 2, 3, 1, 4, 5, 2, 3, 6]
  • maximum of subarray 1 = 3
  • subarray 2 = [1, 2, 3, 1, 4, 5, 2, 3, 6]
  • maximum of subarray 2 = 3
  • subarray 3 = [1, 2, 3, 1, 4, 5, 2, 3, 6]
  • maximum of subarray 3 = 4
  • Etc.

TRY IT YOURSELF

ANSWER

This question tests our ability to write a rather straightforward function in Python.

The trick to this is to be careful with Python indexing as it starts with 0 index. So we should loop over our array to its length minus A plus 1. Now, all we need to do is to index into subarrays as iterate over the array.

def subarray_max(array, A):
ans = []
for i in range(len(array)-A+1):
ans.append(max(array[i:i+A]))
return print(*ans)

--

--