Sherlock and MiniMax

This is a problem from HackerRank, is not a complex problem but i think the solution is interesting for the way approach the problem. I will present here at first two versions of the algorithm, one have O(n^2) complexity and the second O(nlogn). I have also a O(n) solution which i need to analyze better, then i will post it as well..

But first thing first, the problem statement (LINK):

Watson gives Sherlock an array A1,A2…AN.
He asks him to find an integer M between P and Q(both inclusive), such that, min {|Ai-M|, 1 ≤ i ≤ N} is maximised. If there are multiple solutions, print the smallest one.

Input Format
The first line contains N. The next line contains space separated N integers, and denote the array A. The third line contains two space separated integers denoting P and Q.

Output Format
In one line, print the required answer.

1 ≤ N ≤ 102
1 ≤ Ai ≤ 109
1 ≤ P ≤ Q ≤ 109

Sample Input

Sample Output

Clearly the solution must be P, Q or one of the deltas betweent the values of the array, we have n-1 delta and we need to check for each of them the min distance for all the n values, which give us an asymptotic complexity of O(n^2), here’s the code:

This code is good enough to clear the testcases provided for the problem, but we can do much better observing that is possible to seek for the solution just searching in the whole range of possible values 1…1e9 the value for which the minmax is satisfied, this can be done with a binary search:

Basically this code will shrink the range of possible solutions until just one is left. The code for the O(n) implementation came from a friend of mine, i will not modify the code to match the way i link it to be formatted &c but i will leave it exacly as Lukasz give it to me:

Well, the code is O(n) if we ignore the O(nlogn) complexity of the sort operation :) But we do of course! The cleaver idea behind this solution is just to seek for the sweet point picking s,p or q depending of the closest distance from the give point to one of the two possible borders for each delta (t[n], and t[n+1]). Thanks to Lukasz for this idea :)

Leave a Reply