706105. Max Diff Elements and Indexes

Medium

Max Diff Elements and Indexes

Summary

The problem is to find the maximum difference between a pair of elements in an array, along with their corresponding indices. This problem involves arrays, mathematical concepts, and algorithmic thinking.

Detailed Explanation

To solve this problem, we will iterate through the array, calculating the differences between adjacent elements. We'll also keep track of the maximum difference and its corresponding indices.

Here's a step-by-step breakdown:

  1. Initialize variables to store the maximum difference (maxDiff) and its corresponding indices (maxIndex1 and maxIndex2).
  2. Iterate through the array, starting from the first element.
  3. For each element, calculate the differences with the previous and next elements (if they exist).
  4. Update maxDiff if the current difference is greater than the previously stored maximum.
  5. Store the indices of the elements that correspond to maxDiff.
  6. Repeat steps 2-5 until the end of the array is reached.

Here's an ASCII art diagram illustrating the process:

[...], e1, e2, ..., en [...]
  |         |
  |  maxDiff  |
  |  (e1 - e0) |
  |  (e2 - e1) |
    ...
  |  (en - en-1) |
  |         |

Time complexity: O(n), where n is the length of the array. Space complexity: O(1), as we only need a few extra variables to store the maximum difference and its indices.

Optimized Solutions

Java

View on GeeksforGeeks
public int maxDiff(int[] arr) {
    int maxDiff = 0;
    int maxIndex1 = 0;
    int maxIndex2 = 0;

    for (int i = 0; i < arr.length; i++) {
        if (i > 0 && Math.abs(arr[i] - arr[i-1]) > maxDiff) {
            maxDiff = Math.abs(arr[i] - arr[i-1]);
            maxIndex1 = i-1;
            maxIndex2 = i;
        }
    }

    return maxDiff;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.