Given an array arr, find the maximum abs(i-j) such that abs(arr[i] - arr[j]) <= k.
After a lot of thought, I came up with the following algorithm,
1) Create a new array of pair<arr[i], i> (say arrayIndexPairs)
2) Sort this arrayIndexPairs based on the array value (first of pair).
3) Build a segment tree on the index (second of pair) with the arrayIndexPairs so that we can answer range max queries
4) for i <- 0 to n-1
4.1) rightIndex = Binary search the array values (first of pair) for ceil(arrayIndexPairs[i].first) in the interval [i+1, n-1]
4.2) int maxIndex = rangeQueryForMax(i+1, rightIndex)
4.3) result = max(result, maxIndex - i);
return result
The complexity is O(n log n)
for the sort + for every element we do a binary search O(log n)
+ rangeQuery
, O(log n)
. The overall time complexity is O(nlogn + n*2*logn)
which is asymptotically O(nlogn)
.
Is the approach correct? Is is possible to formulate a linear time solution? I tried using hashmaps but find it very hard to arrive at a linear solution.