I'm struggling with this problem: you are given an array $A$ of $n$ integers and a number $k \in \mathbb{N} : k \neq 0$. The problem asks to find an algorithm that runs in $\Theta(n)$ that returns the length of the longest subarray $A'$ in $A$ s. t. $\max(A')-\min(A') \leq k$.
For example, in the array $A = \{6, 5, 9, 10, 7, 13, 8, 7, 5, 15\}$ with $k = 6$ the algorithm must return 6, because the subarray $A' = \{9, 10, 7, 13, 8, 7\}$ has length 6 and the difference between its maximum and its minimum is no more than 6.
Another example, with $A = \{1, 3, 5, 2, 3, 1, 7\}$ with $k = 2$ the result is 3, because the subarray $A' = \{2, 3, 1\}$ has length 3 and the difference between its maximum and minimum is less or equal than 2.
So far I tried to build an algorithm that goes like this (it may be buggy, it's just a draft to make my idea of solution clear):
int test(int* arr, int len, int k) {
int minIndex = 0;
int maxIndex = 0;
int start = 0;
int end = 0;
int maxLength = 0;
for (int i = 1; i < len; i++) {
end = i;
// Update the minimum and maximum if necessary while scanning the array
if (arr[i] < arr[minIndex])
minIndex = i;
if (arr[i] > arr[maxIndex])
maxIndex = i;
// Check the new maximum/minimum doesn't make the subarray invalid
if (arr[maxIndex] - arr[minIndex] > k) {
// We broke the subarray, check the length of the longest subarray until now
if (end - start > maxLength)
maxLength = end - start;
// Restart from the second element, then the third, and so on
start++;
maxIndex = minIndex = start;
i = start;
}
}
return maxLength;
}
The main problem with this algorithm is that in the worst case it runs in $\Theta(n^2)$, which doesn't comply with the problem's requests.