Sherlock and MiniMax
Difficulty: Hard

Watson gives Sherlock an array of integers.  Given the endpoints of an integer range, for all $M$ in that inclusive range, determine the minimum( abs(arr[i]-M) for all $1 \le i \le |arr|$) ).  Once that has been determined for all integers in the range, return the $M$ which generated the maximum of those values.  If there are multiple $M$'s that result in that value, return the lowest one.  

For example, your array $arr = [3,5,7,9]$ and your range is from $p=6$ to $q=8$ inclusive.
```
M	|arr[1]-M|	|arr[2]-M|	|arr[3]-M|	|arr[4]-M|	Min
6	   3		   1		   1		   3		 1
7	   4		   2		   0		   2		 0
8	   5		   3		   1		   1		 1
```
We look at the `Min` column and see the maximum of those three values is $1$.  Two $M$'s result in that answer so we choose the lower value, $6$.

**Function Description**  

Complete the *sherlockAndMinimax* function in the editor below.  It should return an integer as described.  

sherlockAndMinimax has the following parameters:  
- *arr*: an array of integers  
- *p*: an integer that represents the lowest value of the range for $M$  
- *q*: an integer that represents the highest value of the range for $M$  

Input Format:
The first line contains an integer $n$, the number of elements in $arr$.  
The next line contains $n$ space-separated integers $arr[i]$.  
The third line contains two space-separated integers $p$ and $q$, the inclusive endpoints for the range of $M$.       


Output Format:
Print the value of $M$ on a line.

Sample Input:
	3
    5 8 14
    4 9


Sample Output:
	4


Python 3 starter code:
#
# Complete the 'sherlockAndMinimax' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
#  1. INTEGER_ARRAY arr
#  2. INTEGER p
#  3. INTEGER q
#

def sherlockAndMinimax(arr, p, q):
    # Write your code here




Reference solution (C++):
###C++  
```cpp  
#include <bits/stdc++.h>
using namespace std;
int n;
int arr[109];
int A, B;
int answer;

//returns the value to be maximised if M=x
int check( int x )
{
   int ret = INT_MAX;
   for( int i = 0; i < n; ++i ) 
      ret =min(ret, abs( x- arr[i] ));
   return ret;
}

// check is x is within limits and if check(x) is better store the answer
void limits( int x )
{
   if( x < A || x > B ) return;
   if(check(x) > check(answer)) answer = x;   
}

int main()
{
   scanf( "%d", &n );
   for( int i = 0; i < n; ++i ) scanf( "%d", &arr[i] );
   scanf( "%d%d", &A, &B );

   answer = A;

   // check for A and B
   limits( A ); 
   limits( B ); 

   for( int i = 0; i < n; ++i ) 
      for( int j = i+1; j < n; ++j ) 
       {
         // check for (A_i + A_j)/2
         limits( (arr[i]+arr[j])/2 );
       }

   printf( "%d\n",answer );

   return 0;
}
```