710277. Maximum selections

Medium

Maximum selections

Slug: maximum-selections--170637 Difficulty: Medium Id: 710277 Topic Tags: Sorting, Algorithms Company Tags: None

Summary

The problem is to find the maximum number of pairs that can be formed from a given array of integers such that each pair has a difference of at most k. This problem involves sorting and optimization techniques.

Detailed Explanation

To solve this problem, we need to first sort the array in ascending order. Then, we initialize two pointers, i and j, to the start and end of the array respectively. We iterate through the array until i meets j. For each iteration, we check if the difference between the elements at indices i and j is less than or equal to k. If it is, we increment the count of pairs and move both pointers towards the center of the array. If not, we only move the pointer that is closer to the other. This ensures that we consider all possible pairs in the array while keeping track of the maximum number of pairs.

Here's a step-by-step breakdown of the solution:

  1. Sort the array in ascending order.
  2. Initialize i and j to 0 and n-1 respectively, where n is the length of the array.
  3. Iterate through the array until i meets j.
  4. For each iteration, check if the difference between the elements at indices i and j is less than or equal to k. If it is:
    • Increment the count of pairs.
    • Move both pointers towards the center of the array (i.e., increment i and decrement j).
  5. If not, move the pointer that is closer to the other.
  6. Repeat steps 4-5 until i meets j.
  7. Return the count of pairs as the maximum number of selections.

Time complexity: O(n log n) due to sorting Space complexity: O(1)

Optimized Solutions

Java

View on GeeksforGeeks
public int maxSelections(int[] arr, int k) {
    Arrays.sort(arr);
    int i = 0, j = arr.length - 1;
    int count = 0;
    while (i < j) {
        if (arr[j] - arr[i] <= k) {
            count++;
            i++;
            j--;
        } else if (arr[j] - arr[i] > k) {
            j--;
        } else {
            i++;
        }
    }
    return count;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.