Problem
You have an array of floating point numbers averages
which is initially empty. You are given an array nums
of n
integers where n
is even.
You repeat the following procedure n / 2
times:
- Remove the smallest element,
minElement
, and the largest elementmaxElement
, fromnums
. - Add
(minElement + maxElement) / 2
toaverages
.
Return the minimum element in averages
.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
2 <= n == nums.length <= 50
n
is even.1 <= nums[i] <= 50
Solution
Method 1 – Sorting and Two Pointers
Intuition
The smallest and largest elements can be efficiently found by sorting the array. By pairing the smallest and largest, then moving inward, we ensure each average is calculated correctly. The minimum of these averages is the answer.
Approach
- Sort the array
nums
in ascending order. - Use two pointers: one at the start (
l
), one at the end (r
). - For each step, calculate the average of
nums[l]
andnums[r]
, add toaverages
. - Move
l
forward andr
backward, repeat until all pairs are processed. - Return the minimum value in
averages
.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n log n)
, due to sorting the array of size n. - 🧺 Space complexity:
O(1)
, as only a few variables are used for pointers and answer.