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 thei-thelement and the(i + K - 1)-thelement (theK-thelement in the subsequence). - Minimize the Difference: Track the minimum of these differences.
Algorithm:
- Sort the array.
- For each index
ifrom0toN - K, calculate the difference betweenA[i+K-1]andA[i]. - Return the minimum of these differences.
Complexity:
- Time Complexity: Sorting the array takes
O(N log N). The sliding window loop takesO(N - K)iterations, which is essentiallyO(N)in the worst case. - Space Complexity: O(1) No extra space used.