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:
- Sort the input array in ascending order.
- Initialize two variables:
max_diffto store the maximum difference found so far, andindex1andindex2to store the indices of the pair with the largest absolute difference. - Iterate through the sorted array, considering each pair of adjacent elements.
- Calculate the absolute difference between the current element and the previous one.
- If the calculated difference is greater than
max_diff, updatemax_diffand setindex1to the index of the previous element andindex2to the current index. - Continue iterating until the end of the array, and return
index1andindex2as 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
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};
}
}