Dare2Solve
The problem requires us to repeatedly find pairs of smallest and largest elements from an array, compute their average, and then find the minimum of these averages. This suggests a strategy where we efficiently maintain and update the smallest and largest elements while iterating through the array.
Sort the Array: Start by sorting the given array nums
of integers.
Iterate through Pairs: Iterate over the sorted array in pairs from both ends towards the center:
minElement
) and largest (maxElement
) elements from the current ends of the array.avg = (minElement + maxElement) / 2
.averages
array.Compute Minimum: After populating the averages
array with all computed averages, find the minimum value in this array.
Return Minimum: Return the computed minimum value from the averages
array as the result.
Time Complexity:
averages
array takes (O(n/2)).Space Complexity:
averages
array.class Solution {
public:
double minimumAverage(std::vector<int>& nums) {
int res = 100;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size() / 2; ++i) {
res = min(res, nums[i] + nums[nums.size() - i - 1]);
}
return res / 2.0;
}
};
class Solution:
def minimumAverage(self, nums: List[int]) -> float:
nums.sort()
res = 100
for i in range(len(nums) // 2):
res = min(res, nums[i] + nums[len(nums) - i - 1])
return res / 2
class Solution {
public double minimumAverage(int[] nums) {
double res = 100;
Arrays.sort(nums);
for (int i = 0; i < nums.length / 2; ++i) {
res = Math.min(res, nums[i] + nums[nums.length - i - 1]);
}
return res / 2;
}
}
/**
* @param {number[]} nums
* @return {number}
*/
var minimumAverage = function (nums) {
var res = 100;
nums.sort((a, b) => a - b);
for (var i = 0; i < nums.length >> 1; ++i) {
res = Math.min(res, nums[i] + nums[nums.length - i - 1]);
}
return res / 2;
};
func minimumAverage(nums []int) float64 {
sort.Ints(nums)
res := 100.0
for i := 0; i < len(nums)/2; i++ {
res = math.Min(res, float64(nums[i]+nums[len(nums)-i-1]))
}
return res / 2
}
public class Solution {
public double MinimumAverage(int[] nums) {
double res = 100;
Array.Sort(nums);
for (int i = 0; i < nums.Length / 2; ++i) {
res = Math.Min(res, nums[i] + nums[nums.Length - i - 1]);
}
return res / 2;
}
}