Given an array of 2 * n elements, the task is to construct and print an array of n element such that the mean of the new array is maximum. Here n is even.
Examples:
Input: arr[] = {3, 1, 2, 3, 8, 6}
Output: 3 6 8Input: arr[] = {3, 2, 3, 8}
Output: 3 8
Approach: Mean of an array is the average of the elements of the same array i.e (∑arr[i]) / n. So, in order for the mean of the array to be maximum, choose the maximum n elements from the array, this can be done by first sorting the array and then choosing the elements starting from the maximum.
Below is the implementation of the above approach:
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Utility function to print the contents // of an array void printArray(int arr[], int n) { for (int i = 0; i < n; i++) cout << arr[i] << " "; } // Function to print the array with // maximum mean void printMaxMean(int arr[], int n) { int newArr[n]; // Sort the original array sort(arr, arr + 2 * n); // Construct new array for (int i = 0; i < n; i++) newArr[i] = arr[i + n]; // Print the resultant array printArray(newArr, n); } // Driver code int main() { int arr[] = { 4, 8, 3, 1, 3, 7, 0, 4 }; int n = sizeof(arr) / sizeof(arr[0]); printMaxMean(arr, n / 2); return 0; } |
4 4 7 8
Recommended Posts:
- Choose k array elements such that difference of maximum and minimum is minimized
- Maximum distinct elements after removing k elements
- Maximum in array which is at-least twice of other elements
- Maximum sum such that no two elements are adjacent
- Maximum value K such that array has at-least K elements that are >= K
- Sum of maximum elements of all subsets
- Maximum sum subsequence with at-least k distant elements
- Maximum Subarray Sum Excluding Certain Elements
- Covering maximum array elements with given value
- Maximum set bit sum in array without considering adjacent elements
- Maximum difference between two subsets of m elements
- Count of subsequences having maximum distinct elements
- Maximum elements that can be made equal with k updates
- Maximum sum of increasing order elements from n arrays
- Maximum sum in circular array such that no two elements are adjacent
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



