Problem Description
Given an even-length array of integers called nums, repeatedly remove the smallest and largest elements from nums and compute their average. Append each computed average to an initially empty array called averages. After performing this procedure n/2 times (where n is the length of nums), return the minimum value among all the averages.
Key Insights
- Sorting the array makes it easy to consistently retrieve the smallest and largest available elements.
- After sorting, the smallest element is at the beginning and the largest at the end.
- Pairing the ith smallest with the ith largest (using two pointers) directly simulates the removal process.
- The solution then involves computing averages for these pairs and determining the minimum average.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting the array. Space Complexity: O(1) extra space if sorting is done in-place (or O(n) if extra space is used for the sorted copy).
Solution
The algorithm starts by sorting the input array. Two pointers (one starting at the beginning and the other at the end of the array) are then used to form pairs of the smallest and largest elements that remain. For each pair, the average is computed and tracked if it is the smallest average seen so far. Finally, the minimum average is returned. This approach avoids the overhead of repeatedly removing elements from the array, thus optimizing the process.