VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-difference-with-fixed-index-difference/

⇱ Find maximum difference between elements having a fixed index difference of K - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find maximum difference between elements having a fixed index difference of K

Last Updated : 16 Nov, 2023

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:

  • Initialize a variable max_diff to track the maximum difference and set it to a very small value initially.
  • Iterate through the array from the beginning to the (last - K)th element
    • For each index, i, calculate the absolute difference between (arr[i] - arr[i + k]).
    • Compare the calculated difference with the current max_diff. If the calculated difference is greater than max_diff, update max_diff with the new value.
  • After the iteration, max_diff will contain the maximum difference between elements with a K-index difference.
  • Return max_diff

Below is the implementation of the approach:


Output
5

Time Complexity: O(N), where N is the number of elements in the array arr[]
Auxiliary Space: O(1)

Comment