C++ program to find maximum possible median of elements whose sum is s

C++Server Side ProgrammingProgramming

Suppose we have two numbers n and s. We have to find the maximum possible median of an array of n non-negative elements, such that the sum of elements is same as s.

So, if the input is like n = 3; s = 5, then the output will be 2, because for the array [1, 2, 2], the sum is 5 and median is 2.

Steps

To solve this, we will follow these steps −

m := floor of (n / 2) + 1
return floor of (s / m)

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

int solve(int n, int s) {
   int m = n / 2 + 1;
   return s / m;
}
int main() {
   int n = 3;
   int s = 5;
   cout << solve(n, s) << endl;
}

Input

3, 5

Output

2
raja
Updated on 03-Mar-2022 11:00:07

Advertisements