• Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
Wednesday, February 8, 2023
  • Login
Zeroplusfour
No Result
View All Result
  • Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
  • Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
No Result
View All Result
Zeroplusfour
No Result
View All Result
Home Code Solutions Hackerrank Algorithms

Sherlock and MiniMax – HackerRank Solution

Sherlock and MiniMax - HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

bhautik bhalala by bhautik bhalala
May 27, 2022
Reading Time: 1 min read
0
15 Days to learn SQL Hard SQL(Advanced)-Solution

15 Days to learn SQL Hard SQL(Advanced)-Solution alt text

Spread the love

Table of Contents

  • Sherlock and MiniMax – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
  • Solutions of Algorithms Data Structures Hard HackerRank:
    • Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts
  • C++ Sherlock and MiniMax HackerRank Solution
  • Java Sherlock and MiniMax HackerRank Solution
  • Python 3 Sherlock and MiniMax HackerRank Solution
  • Python 2 Sherlock and MiniMax HackerRank Solution
  • C Sherlock and MiniMax HackerRank Solution
    • Warmup Implementation Strings Sorting Search Graph Theory Greedy Dynamic Programming Constructive Algorithms Bit Manipulation Recursion Game Theory NP Complete Debugging
    • Leave a comment below
      • Related posts:

Sherlock and MiniMax – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

Solutions of Algorithms Data Structures Hard HackerRank:

Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts

C++ Sherlock and MiniMax HackerRank Solution


Copy Code Copied Use a different Browser

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

#define REP(i,a,b) for(i=a;i<b;i++)
#define rep(i,n) REP(i,0,n)

#define mygc(c) (c)=getchar_unlocked()
#define mypc(c) putchar_unlocked(c)

void reader(int *x){int k,m=0;*x=0;for(;;){mygc(k);if(k=='-'){m=1;break;}if('0'<=k&&k<='9'){*x=k-'0';break;}}for(;;){mygc(k);if(k<'0'||k>'9')break;*x=(*x)*10+k-'0';}if(m)(*x)=-(*x);}
void reader(int *x, int *y){reader(x);reader(y);}
void writer(int x, char c){int i,sz=0,m=0;char buf[10];if(x<0)m=1,x=-x;while(x)buf[sz++]=x%10,x/=10;if(!sz)buf[sz++]=0;if(m)mypc('-');while(sz--)mypc(buf[sz]+'0');mypc(c);}

int N, A[1000], P, Q;

int test[100000], test_size;

int check(int k){
  int i;
  int res = 2000000000;
  rep(i,N) res = min(res, abs(A[i]-k));
  return res;
}

int main(){
  int i, j, k;
  int res, mx;

  reader(&N);
  rep(i,N) reader(A+i);
  reader(&P,&Q);

  sort(A,A+N);

  mx = -1;
  test_size = 0;
  test[test_size++] = P;
  test[test_size++] = Q;
  REP(i,1,N) {
    k = (A[i] + A[i-1])/2;
    if(P<=k && k<=Q) test[test_size++] = k;
    k = (A[i] + A[i-1])/2 + 1;
    if(P<=k && k<=Q) test[test_size++] = k;
  }
  sort(test,test+test_size);

  mx = -1;
  rep(i,test_size){
    k = check(test[i]);
    if(k > mx) mx = k, res = test[i];
  }
  writer(res, '\n');

  return 0;
}

Java Sherlock and MiniMax HackerRank Solution


Copy Code Copied Use a different Browser

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;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Egor Kulikov (egor@egork.net)
 */
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;
	}

}

 



Python 3 Sherlock and MiniMax HackerRank Solution


Copy Code Copied Use a different Browser

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)



Python 2 Sherlock and MiniMax HackerRank Solution


Copy Code Copied Use a different Browser

n = input()
a = sorted(map(int, raw_input().split()))
def f(m):
    res = 2e9
    for x in a:
        res = min(res, abs(x-m))
    return res
p,q = map(int, raw_input().split())
res,maks = p,f(p)
for i in xrange(1,n):
    m = (a[i]+a[i-1])/2
    if m < p or m > q:
        continue
    if min(m-a[i-1], a[i]-m) > maks:
        maks = min(m-a[i-1], a[i]-m)
        res = m
    elif min(m-a[i-1], a[i]-m) == maks:
        res = min(res,m)
if f(q) > maks:
    maks = f(q)
    res = q
elif f(q) == maks:
    res = min(res,q)
print res



C Sherlock and MiniMax HackerRank Solution


Copy Code Copied Use a different Browser

#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;
}

 

Warmup
Implementation
Strings
Sorting
Search
Graph Theory
Greedy
Dynamic Programming
Constructive Algorithms
Bit Manipulation
Recursion
Game Theory
NP Complete
Debugging

Leave a comment below

 

Related posts:

15 Days to learn SQL Hard SQL(Advanced)-SolutionAlmost Integer Rock Garden – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionCaesar Cipher – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionDemanding Money- HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionKth Ancestor – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionAlex vs Fedor – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionChief Hopper – HackerRank Solution
Tags: Cc++14full solutionGoHackerRank Solutionjavajava 15java 7java 8java8javascriptpypy 3Python 2python 3Sherlock and MiniMax
ShareTweetPin
bhautik bhalala

bhautik bhalala

Related Posts

Leetcode All Problems Solutions
Code Solutions

Exclusive Time of Functions – LeetCode Solution

by admin
October 5, 2022
0
41

Exclusive Time of Functions - LeetCode Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions...

Read more
Leetcode All Problems Solutions

Smallest Range Covering Elements from K Lists – LeetCode Solution

October 5, 2022
32
Leetcode All Problems Solutions

Course Schedule III – LeetCode Solution

October 5, 2022
27
Leetcode All Problems Solutions

Maximum Product of Three Numbers – LeetCode Solution

September 11, 2022
53
Leetcode All Problems Solutions

Task Scheduler – LeetCode Solution

September 11, 2022
119
Leetcode All Problems Solutions

Valid Triangle Number – LeetCode Solution

September 11, 2022
28
Next Post
15 Days to learn SQL Hard SQL(Advanced)-Solution

Accessory Collection - HackerRank Solution

15 Days to learn SQL Hard SQL(Advanced)-Solution

Team Formation - HackerRank Solution

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may also like

15 Days to learn SQL Hard SQL(Advanced)-SolutionAlmost Integer Rock Garden – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionCaesar Cipher – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionDemanding Money- HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionKth Ancestor – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionAlex vs Fedor – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionChief Hopper – HackerRank Solution

Categories

  • Algorithms
  • Anime
  • Biography
  • Business
  • Code Solutions
  • Cosmos
  • Countdowns
  • Culture
  • Economy
  • Education
  • Entertainment
  • Finance
  • Games
  • Hackerrank
  • Health
  • How to
  • Investment
  • LeetCode
  • Lifestyle
  • LINUX SHELL
  • Manga
  • News
  • Opinion
  • Politics
  • Sports
  • SQL
  • Tech
  • Travel
  • Uncategorized
  • Updates
  • World
  • DMCA
  • Home
  • My account
  • Privacy Policy
  • Top Posts

Recent Blogs

Leetcode All Problems Solutions

Exclusive Time of Functions – LeetCode Solution

October 5, 2022
Leetcode All Problems Solutions

Smallest Range Covering Elements from K Lists – LeetCode Solution

October 5, 2022
Biography

Shakti Kapoor Net Worth, Age, Height , Achivements and more

September 8, 2022
0
10 BEST BOLLYWOOD MOVIES OF 2021 alt text
Updates

10 BEST BOLLYWOOD MOVIES OF 2021

May 31, 2022
4
15 Days to learn SQL Hard SQL(Advanced)-Solution
Code Solutions

Plus Minus- HackerRank Solution

May 31, 2022
2
15 Days to learn SQL Hard SQL(Advanced)-Solution
Algorithms

Build a String – HackerRank Solution

May 24, 2022
622

© 2022 ZeroPlusFour - Latest News & Blog.

No Result
View All Result
  • Home
  • Category
    • Business
    • Culture
    • Economy
    • Lifestyle
    • Health
    • Travel
    • Opinion
    • Politics
    • Tech
  • Landing Page
  • Support Forum
  • Contact Us

© 2022 ZeroPlusFour - Latest News & Blog.

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT
Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?