SUBS - Editorial

Problem Link - Fair distribution Practice Problem in Jump from 2* to 3*

Problem Statement:

Given an array A_1,A_2,..,A_N of size N and an integer K. You want to choose K elements from array A such that difference between maximum and minimum element ( from chosen elements) is minimum.

Approach:

  • Sort the array: Sorting arranges the elements in increasing order, and consecutive elements in this sorted array are more likely to have the smallest differences.
  • Sliding Window of Size K: Once the array is sorted, the problem reduces to finding the minimum difference between the first and last elements of any consecutive subsequence of length K.
  • Iterate through the array: For each possible starting index i, calculate the difference between the i-th element and the (i + K - 1)-th element (the K-th element in the subsequence).
  • Minimize the Difference: Track the minimum of these differences.

Algorithm:

  1. Sort the array.
  2. For each index i from 0 to N - K, calculate the difference between A[i+K-1] and A[i].
  3. Return the minimum of these differences.

Complexity:

  • Time Complexity: Sorting the array takes O(N log N). The sliding window loop takes O(N - K) iterations, which is essentially O(N) in the worst case.
  • Space Complexity: O(1) No extra space used.