702648. Count the pairs with maximum difference
Easy
Count the Pairs with Maximum Difference
Summary
Given an array arr of integers, count the number of pairs (i, j) such that the difference between their values is maximum. The array contains distinct elements.
Detailed Explanation
The problem can be solved by iterating over all possible pairs in the array and keeping track of the maximum difference found so far. To make this more efficient, we first sort the array in ascending order. Then, we initialize a variable max_diff to store the maximum difference and count to store the count of such pairs.
Here's the step-by-step breakdown:
- Sort the array
arrin ascending order. - Initialize
max_diffto 0 andcountto 0. - Iterate over all possible pairs
(i, j)in the array:- Calculate the difference between the values at indices
iandj. - If this difference is greater than
max_diff, updatemax_diffand setcountto 1. - Else if this difference is equal to
max_diff, incrementcount.
- Calculate the difference between the values at indices
- Return the value of
count.
Time complexity: O(n log n) due to sorting, where n is the size of the array.
Space complexity: O(1), as we only use a constant amount of space to store max_diff and count.
Optimized Solutions
Java
public int countPairs(int[] arr) {
Arrays.sort(arr);
int max_diff = 0;
int count = 0;
for (int i = 0; i < arr.length - 1; i++) {
int diff = arr[i + 1] - arr[i];
if (diff > max_diff) {
max_diff = diff;
count = 1;
} else if (diff == max_diff) {
count++;
}
}
return count;
}