Leetcode 3194. Minimum Average of Smallest and Largest Elements
Given an array, you need to find the minimum possible average of the smallest and largest elements in any subsequence of the array of length at least two.
The goal is to minimize the average of the smallest and largest elements of any subsequence of length at least two. To achieve this efficiently, you can follow these steps:
Here’s the C++ code to solve the problem:
#include <vector>
#include <algorithm>
#include <iostream>
double minimumSubsequenceAverage(std::vector<int>& nums) {
// First, sort the array
std::sort(nums.begin(), nums.end());
// The smallest element will be the first element in the sorted array
int smallest = nums.front();
// The largest element will be the last element in the sorted array
int largest = nums.back();
// Calculate and return the average of smallest and largest
return (smallest + largest) / 2.0;
}
int main() {
// Example usage:
std::vector<int> nums = {3, 1, 4, 1, 5, 9};
double result = minimumSubsequenceAverage(nums);
std::cout << "Minimum average of smallest and largest elements: " << result << std::endl;
return 0;
}
Overall, the time complexity is dominated by the sorting step, so the overall time complexity is (O(n \log n)). This is efficient and suitable for even relatively large arrays.
By following this strategy, your code will efficiently find the minimum possible average of the smallest and largest elements in any subsequence of the given array.
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?