Given an array of N positive integers, ranging from index 0 to N - 1, how can I find a contiguous subarray of length K with the minimum range possible. In other words, max(subarray) - min(subarray) is minimised. If there are multiple answers, any is fine.
For example, find the subarray of length 2 with the smallest range from [4, 1, 2, 6]
The answer would be [1, 2] as 2 - 1 = 1 gives the smallest range of all possible contiguous subarrays.
Other subarrays are [4, 1] (range 3), [2, 6] (range 4)
I'm using python and so far I've tried a linear search with min() max() functions and it just doesn't seem efficient to do so. I've thought of using a minheap but I'm not sure how you would implement this and I'm not even sure if it would work. Any help would be much appreciated.
edit: code added
# N = length of array_of_heights, K = subarray length
N, K = map(int, input().split(' '))
array_of_heights = [int(i) for i in input().split(' ')]
min_min = 100000000000000000000
# iterates through all subarrays in the array_of_heights of length K
for i in range(N + 1 - K):
subarray = land[i : i + K]
min_min = min(max(subarray)-min(subarray), min_min)
print(min_min)