Leetcode 3194. Minimum Average of Smallest and Largest Elements
Given an array of integers, find the minimum possible average of the smallest and largest elements of any subarray of length at least two. Your task is to return that minimum average.
To solve this problem efficiently, we can follow these steps:
public class Solution {
public double findMinAverage(int[] nums) {
double minAverage = Double.MAX_VALUE;
for (int i = 0; i < nums.length; i++) {
int minElement = nums[i];
int maxElement = nums[i];
for (int j = i + 1; j < nums.length; j++) {
minElement = Math.min(minElement, nums[j]);
maxElement = Math.max(maxElement, nums[j]);
double currentAverage = (minElement + maxElement) / 2.0;
minAverage = Math.min(minAverage, currentAverage);
}
}
return minAverage;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums = {3, 1, 4, 1, 5, 9, 2};
System.out.println(sol.findMinAverage(nums)); // Should output the minimum average.
}
}
n
times.n-1
times (on average).(n*(n-1))/2
subarrays.Thus, the overall time complexity is O(n^2), where n
is the length of the array. This is the best we can do for evaluating all subarrays longer than one element.
The space complexity is O(1) since we are using only a few extra variables and not any additional space that scales with input size.
This solution efficiently calculates the minimum possible average of the smallest and largest elements in all possible subarrays of length at least two, adhering to the time and space constraints expected for the problem’s requirements.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?