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 :
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
Sparse Arrays
There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example: strings=['ab', 'ab', 'abc'] queries=['ab', 'abc', 'bc'] There are instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array, results=[2,1,0]. Fun
View Solution →Array Manipulation
Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu
View Solution →Print the Elements of a Linked List
This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Function Description: Complete the printLinkedList function in the editor below. printLinkedList has the following parameter(s): 1.SinglyLinkedListNode
View Solution →Insert a Node at the Tail of a Linked List
You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink
View Solution →Insert a Node at the head of a Linked List
Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below
View Solution →Insert a node at a specific position in a linked list
Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e
View Solution →