Sherlock and MiniMax


Problem Statement :


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

For example, your array  and your range is from  to  inclusive.


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 
- q: an integer that represents the highest value of the range for 

Input Format

The first line contains an integer , the number of elements in .
The next line contains  space-separated integers .
The third line contains two space-separated integers  and , the inclusive endpoints for the range of .

Output Format

Print the value of  M on a line.



Solution :



title-img


                            Solution in C :

In   C  :





#include<stdio.h>
#include<stdlib.h>

void quicksort( long int *x,long int first,long int last){
    long int pivot,j,temp,i;

     if(first<last){
         pivot=first;
         i=first;
         j=last;

         while(i<j){
             while(x[i]<=x[pivot]&&i<last)
                 i++;
             while(x[j]>x[pivot])
                 j--;
             if(i<j){
                 temp=x[i];
                  x[i]=x[j];
                  x[j]=temp;
             }
         }

         temp=x[pivot];
         x[pivot]=x[j];
         x[j]=temp;
         quicksort(x,first,j-1);
         quicksort(x,j+1,last);

    }
}



long int searchLeft(long int *a,long int N,long int e)
{
    long int i=0;
    while(a[i]<e && i!=N-1)
        i++;
    if(a[i]<e) return -1;
    else return i;    
}

long int searchRight(long int *a,long int N,long int e)
{
    long int i=N-1;
    while(a[i]>e && i!=0)
        i--;
    if(a[i]>e) return -1;
    else return i;
}

long int min(long int a,long int b)
{
    if(a>b)
        return b;
    else return a;
}

long int func(long int *a,long int N,long int x,long int y,long int l,long int r)
{
    long int maxDiff=-1,i,ans;
    for(i=x;i<y;i++)
    {
        long int diff=(a[i+1]-a[i])/2;
        if(diff>maxDiff)
        {
            ans=(a[i+1]+a[i])/2;
            maxDiff=diff;
        }    
        
    }
    if(x!=0 && a[x]-a[x-1]>=2*maxDiff && a[x]+a[x-1]>2*l)
    {
        ans=(a[x]+a[x-1])/2;
        maxDiff=(a[x]-a[x-1])/2;
        
    }    
        
    
    if(x==0 && a[x]-l >= maxDiff)
    {
        ans=l;
        maxDiff=a[x]-l;
    }
        
    if(x!=0 && min(a[x]-l,l-a[x-1])>=maxDiff)
    {
        ans=l;
        maxDiff=min(a[x]-l,l-a[x-1]);
    }    
    
    if(y!=N-1 && a[y+1]-a[y]>2*maxDiff && a[y+1]+a[y]<2*r)
    {
        ans=(a[y]+a[y+1])/2;
        maxDiff=(a[y+1]-a[y])/2;
    }
    
    if(y==N-1 && r-a[y]>maxDiff)
    {
        ans=r;
        maxDiff=r-a[y];
    }
         
    if(y!=N-1 && min(r-a[y],a[y+1]-r)>maxDiff)
        ans=r;
        
    
    
    return ans;
}

int main()
{
    long int N,i,l,r,x,y,ans;
    scanf("%ld",&N);
    long int a[N];
    for(i=0;i<N;i++)
        scanf("%ld",a+i);
    scanf("%ld %ld",&l,&r);
    quicksort(a,0,N-1);
    x=searchLeft(a,N,l);
    y=searchRight(a,N,r);
    
    if(x==-1)
        ans=r;
    else if(y==-1)
        ans=l;
    else
        ans=func(a,N,x,y,l,r);
    
    
    printf("%ld\n",ans);
    return 0;
}
                        


                        Solution in C++ :

In  C ++  :








#define _CRT_SECURE_NO_WARNINGS
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <set>
#include <map>
#include <queue>
#include <iostream>
#include <sstream>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <cstring>
#include <cctype>
#include <cassert>
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define rer(i,l,u) for(int (i)=(int)(l);(i)<=(int)(u);++(i))
#define reu(i,l,u) for(int (i)=(int)(l);(i)<(int)(u);++(i))
#if defined(_MSC_VER) || __cplusplus > 199711L
#define aut(r,v) auto r = (v)
#else
#define aut(r,v) typeof(v) r = (v)
#endif
#define each(it,o) for(aut(it, (o).begin()); it != (o).end(); ++ it)
#define all(o) (o).begin(), (o).end()
#define pb(x) push_back(x)
#define mp(x,y) make_pair((x),(y))
#define mset(m,v) memset(m,v,sizeof(m))
#define INF 0x3f3f3f3f
#define INFL 0x3f3f3f3f3f3f3f3fLL
using namespace std;
typedef vector<int> vi; typedef pair<int,int> pii; typedef vector<pair<int,int> > vpii;
typedef long long ll; typedef vector<long long> vl; typedef pair<long long,long long> pll; typedef vector<pair<long long,long long> > vpll;
typedef vector<string> vs; typedef long double ld;
template<typename T, typename U> inline void amin(T &x, U y) { if(y < x) x = y; }
template<typename T, typename U> inline void amax(T &x, U y) { if(x < y) x = y; }

int A[102];
int main() {
	int N;
	scanf("%d", &N);
	rep(i, N) scanf("%d", &A[i]);
	int P, Q;
	scanf("%d%d", &P, &Q);
	A[N] = P; A[N+1] = Q;
	pair<int, int> ans = mp(-INF, INF);
	rep(i, N+2) rep(j, i+1) rer(d, -1, 1) {
		int m = (A[i] + A[j]) / 2 + d;
		if(!(P <= m && m <= Q)) continue;
		int x = INF;
		rep(i, N)
			amin(x, abs(A[i] - m));
		amax(ans, mp(x, -m));
	}
	printf("%d\n", -ans.second);
	return 0;
}
                    


                        Solution in Java :

In  Java :






import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.InputStream;
import java.util.NoSuchElementException;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;


public class Solution {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);
		SherlockAndMiniMax solver = new SherlockAndMiniMax();
		solver.solve(1, in, out);
		out.close();
	}
}

class SherlockAndMiniMax {
    public void solve(int testNumber, InputReader in, OutputWriter out) {
		int count = in.readInt();
		int[] array = IOUtils.readIntArray(in, count);
		int min = in.readInt();
		int max = in.readInt();
		int best = -1;
		int at = -1;
		Arrays.sort(array);
		int candidate = Integer.MAX_VALUE;
		for (int i : array)
			candidate = Math.min(candidate, Math.abs(min - i));
		if (candidate > best || candidate == best && at > min) {
			at = min;
			best = candidate;
		}
		candidate = Integer.MAX_VALUE;
		for (int i : array)
			candidate = Math.min(candidate, Math.abs(max - i));
		if (candidate > best || candidate == best && at > max) {
			at = max;
			best = candidate;
		}
		for (int i = 1; i < count; i++) {
			int current = (array[i] + array[i - 1]) / 2;
			if (current < min || current > max) {
				continue;
			}
			candidate = current - array[i - 1];
			if (candidate > best || candidate == best && at > current) {
				at = current;
				best = candidate;
			}
		}
		out.printLine(at);
	}
}

class InputReader {

	private InputStream stream;
	private byte[] buf = new byte[1024];
	private int curChar;
	private int numChars;
	private SpaceCharFilter filter;

	public InputReader(InputStream stream) {
		this.stream = stream;
	}

	public int read() {
		if (numChars == -1)
			throw new InputMismatchException();
		if (curChar >= numChars) {
			curChar = 0;
			try {
				numChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (numChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int readInt() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public boolean isSpaceChar(int c) {
		if (filter != null)
			return filter.isSpaceChar(c);
		return isWhitespace(c);
	}

	public static boolean isWhitespace(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	public interface SpaceCharFilter {
		public boolean isSpaceChar(int ch);
	}
}

class OutputWriter {
	private final PrintWriter writer;

	public OutputWriter(OutputStream outputStream) {
		writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
	}

	public OutputWriter(Writer writer) {
		this.writer = new PrintWriter(writer);
	}

	public void close() {
		writer.close();
	}

	public void printLine(int i) {
		writer.println(i);
	}
}

class IOUtils {

	public static int[] readIntArray(InputReader in, int size) {
		int[] array = new int[size];
		for (int i = 0; i < size; i++)
			array[i] = in.readInt();
		return array;
	}

}
                    


                        Solution in Python : 
                            
In   Python3 :






N = int(input())
A = [int(c) for c in input().split()[:N]]
P, Q = [int(c) for c in input().split()[:2]]

a = sorted(A)
max_point = P
max_distance = min(abs(i - P) for i in a)
for i in range(len(a) - 1):
    if a[i] > Q or a[i+1] < P:
        continue
    m = int((a[i] + a[i+1]) / 2)
    if m < P:
        point = P
        distance = a[i+1] - P
    elif m > Q:
        point = Q
        distance = Q - a[i]
    else: #m >= P and m <= Q:
        point = m
        distance = m - a[i]
    if distance > max_distance:
        max_point = point
        max_distance = distance
point = Q
distance = min(abs(i - Q) for i in a)
if distance > max_distance:
    max_point = point
    max_distance = distance
print(max_point)
                    


View More Similar Problems

Array and simple queries

Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty

View Solution →

Median Updates

The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o

View Solution →

Maximum Element

You have an empty sequence, and you will be given N queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. Input Format The first line of input contains an integer, N . The next N lines each contain an above mentioned query. (It is guaranteed that each

View Solution →

Balanced Brackets

A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of bra

View Solution →

Equal Stacks

ou have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times. Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of

View Solution →

Game of Two Stacks

Alexa has two stacks of non-negative integers, stack A = [a0, a1, . . . , an-1 ] and stack B = [b0, b1, . . . , b m-1] where index 0 denotes the top of the stack. Alexa challenges Nick to play the following game: In each move, Nick can remove one integer from the top of either stack A or stack B. Nick keeps a running sum of the integers he removes from the two stacks. Nick is disqualified f

View Solution →