703264. Maximum difference Indexes

Easy

Maximum Difference Indexes

Slug: maximum-difference-10429 Difficulty: Easy Id: 703264 Topic Tags: Arrays, Map, Data Structures Company Tags: None

Summary

Given an array of integers, find the maximum difference between any two elements in the array. The problem requires you to identify the pair with the largest absolute difference and return its indices.

Detailed Explanation

To solve this problem, we can use a simple approach involving sorting the array and then iterating through it to find the maximum difference. Here's a step-by-step breakdown:

  1. Sort the input array in ascending order.
  2. Initialize two variables: max_diff to store the maximum difference found so far, and index1 and index2 to store the indices of the pair with the largest absolute difference.
  3. Iterate through the sorted array, considering each pair of adjacent elements.
  4. Calculate the absolute difference between the current element and the previous one.
  5. If the calculated difference is greater than max_diff, update max_diff and set index1 to the index of the previous element and index2 to the current index.
  6. Continue iterating until the end of the array, and return index1 and index2 as the indices of the pair with the maximum difference.

Time complexity: O(n log n) due to sorting Space complexity: O(1), as we only use a few extra variables

Optimized Solutions

Java

View on GeeksforGeeks
public class Solution {
    public int[] maxDifference(int[] arr) {
        Arrays.sort(arr);
        int max_diff = 0;
        int index1 = -1, index2 = -1;
        for (int i = 1; i < arr.length; i++) {
            int diff = Math.abs(arr[i] - arr[i-1]);
            if (diff > max_diff) {
                max_diff = diff;
                index1 = i - 1;
                index2 = i;
            }
        }
        return new int[]{index1, index2};
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.