
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Maximize the median of an array in C++
Problem statement
Given an array arr[] of N elements and an integer K where K < N. The task is to insert K integer elements to the same array such that the median of the resultant array is maximized
If input array is {1, 3, 2, 5} and k = 3 then−
- Sorted array becomes {1, 2, 3, 5}
- Insert 3 elements that are greater than 5. After this operation array becomes {1, 2, 3, 5, 6, 6, 6}
- Median of the new array is 5
Algorithm
1. In order to maximize the median of the resultant array, all the elements that need to be inserted must be greater than the maximum element from the array 2. Sort the array and the median of the array will be arr[size / 2] if the size is odd else (arr[(size / 2) – 1] + arr[size / 2]) / 2
Example
#include <bits/stdc++.h> using namespace std; double getMaxMedian(int *arr, int n, int k){ int newSize = n + k; double median; sort(arr, arr + n); if (newSize % 2 == 0) { median = (arr[(newSize / 2) - 1] + arr[newSize / 2]) / 2; return median; } median = arr[newSize / 2]; return median; } int main(){ int arr[] = {1, 3, 2, 5}; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << "Max median = " << getMaxMedian(arr, n, k) << endl; return 0; }
Output
When you compile and execute the above program. It generates the following output−
Max median = 5
- Related Articles
- Maximize the median of the given array after adding K elements to the same array in C++
- Maximize the bitwise OR of an array in C++
- Calculating median of an array in JavaScript
- Program for Mean and median of an unsorted array in C++
- Program to Find Out Median of an Integer Array in C++
- Maximize value of (arr[i] – i) – (arr[j] – j) in an array in C++
- Calculating median of an array JavaScript
- Rearrange an Array to Maximize i*arr[i] using C++
- Maximize the sum of array by multiplying prefix of array with -1 in C++
- Maximize elements using another array in C++
- Maximize array sum after K negation in C++
- Reverse Subarray To Maximize Array Value in C++
- Find Mean and Median of an unsorted Array in Java
- Maximize array elements up to given numbers in C++
- Maximize the sum of selected numbers from an array to make it empty

Advertisements