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:

  1. Sort the array arr in ascending order.
  2. Initialize max_diff to 0 and count to 0.
  3. Iterate over all possible pairs (i, j) in the array:
    • Calculate the difference between the values at indices i and j.
    • If this difference is greater than max_diff, update max_diff and set count to 1.
    • Else if this difference is equal to max_diff, increment count.
  4. 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

View on GeeksforGeeks
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;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.