![]() |
VOOZH | about |
Given an integer K and an unsorted array of integers arr[], find the maximum difference between elements in the array having a fixed index difference of K.
Examples:
Input: arr[] = [2, 9, 7, 4, 6, 8, 3], K = 2
Output: 5
Explanation: The maximum absolute difference with an index difference of two is 5, which occurs between arr[0] and arr[2]Input: arr[] = [5, 1, 9, 3, 7, 8, 2, 4], K = 3
Output: 6
Explanation: The maximum absolute difference with an index difference of three is 6, which occurs between arr[1] and arr[4]
Approach: The problem can be solved using the following approach:
Iterate through the array, keeping track of the absolute current difference and the maximum difference encountered so far. If the absolute current difference is greater than maximum difference, then update the maximum difference.
Steps to solve the problem:
Below is the implementation of the approach:
5
Time Complexity: O(N), where N is the number of elements in the array arr[]
Auxiliary Space: O(1)