Find largest median of a sub array with length at least K
Last Updated :
27 May, 2024
Given an array arr[] of length N (1<= arr[i] <= N) and an integer K. The task is to find the largest median of any subarray in arr[] of at least K size.
Examples:
Input: arr[] = {1, 2, 3, 2, 1}, K = 3
Output: 2
Explanation: Here the median of all possible sub arrays with length >= K is 2, so the maximum median is 2.
Input: arr[] = {1, 2, 3, 4}, K = 2
Output: 3
Explanation: Here the median of sub array( [3. 4] ) = 3 which is the maximum possible median.
Naive Approach: Go through all the sub-arrays with length at least K in arr[] and find the median of each sub-array and get the maximum median.
Below is the implementation of the above approach.
C++
// C++ code to find the maximum median
// of a sub array having length at least K.
#include <bits/stdc++.h>
using namespace std;
// Function to find the maximum median
// of a sub array having length at least k.
int maxMedian(int arr[], int N, int K)
{
// Variable to keep track
// of maximum median.
int mx_median = -1;
// Go through all the sub arrays
// having length at least K.
for (int i = 0; i < N; i++) {
for (int j = i + K - 1; j < N; j++) {
int len = j - i + 1;
int temp[len];
// Copy all elements of
// arr[i ... j] to temp[].
for (int k = i; k <= j; k++)
temp[k - i] = arr[k];
// Sort the temp[] array
// to find the median.
sort(temp, temp + len);
mx_median = max(mx_median,
temp[(len - 1)
/ 2]);
}
}
return mx_median;
}
// Driver code
int main()
{
int arr[] = { 1, 2, 3, 2, 1 };
int N = sizeof(arr) / sizeof(arr[0]);
int K = 3;
// Function Call
cout << maxMedian(arr, N, K);
return 0;
}
Java
// Java code to find the maximum median
// of a sub array having length at least K.
import java.util.*;
public class GFG
{
// Function to find the maximum median
// of a sub array having length at least k.
static int maxMedian(int arr[], int N, int K)
{
// Variable to keep track
// of maximum median.
int mx_median = -1;
// Go through all the sub arrays
// having length at least K.
for (int i = 0; i < N; i++) {
for (int j = i + K - 1; j < N; j++) {
int len = j - i + 1;
int temp[] = new int[len];
// Copy all elements of
// arr[i ... j] to temp[].
for (int k = i; k <= j; k++)
temp[k - i] = arr[k];
// Sort the temp[] array
// to find the median.
Arrays.sort(temp);
mx_median = Math.max(mx_median,
temp[(len - 1)
/ 2]);
}
}
return mx_median;
}
// Driver code
public static void main(String args[])
{
int arr[] = { 1, 2, 3, 2, 1 };
int N = arr.length;
int K = 3;
// Function Call
System.out.println(maxMedian(arr, N, K));
}
}
// This code is contributed by Samim Hossain Mondal.
Python
# Python code for the above approach
# Function to find the maximum median
# of a sub array having length at least k.
def maxMedian(arr, N, K):
# Variable to keep track
# of maximum median.
mx_median = -1;
# Go through all the sub arrays
# having length at least K.
for i in range(N):
for j in range(i + K - 1, N):
_len = j - i + 1;
temp = [0] * _len
# Copy all elements of
# arr[i ... j] to temp[].
for k in range(i, j + 1):
temp[k - i] = arr[k];
# Sort the temp[] array
# to find the median.
temp.sort()
mx_median = max(mx_median, temp[((_len - 1) // 2)]);
return mx_median;
# Driver code
arr = [1, 2, 3, 2, 1];
N = len(arr)
K = 3;
# Function Call
print(maxMedian(arr, N, K));
# This code is contributed by Saurabh Jaiswal
C#
// C# code to find the maximum median
// of a sub array having length at least K.
using System;
class GFG
{
// Function to find the maximum median
// of a sub array having length at least k.
static int maxMedian(int []arr, int N, int K)
{
// Variable to keep track
// of maximum median.
int mx_median = -1;
// Go through all the sub arrays
// having length at least K.
for (int i = 0; i < N; i++) {
for (int j = i + K - 1; j < N; j++) {
int len = j - i + 1;
int []temp = new int[len];
// Copy all elements of
// arr[i ... j] to temp[].
for (int k = i; k <= j; k++)
temp[k - i] = arr[k];
// Sort the temp[] array
// to find the median.
Array.Sort(temp);
mx_median = Math.Max(mx_median,
temp[(len - 1)
/ 2]);
}
}
return mx_median;
}
// Driver Code:
public static void Main()
{
int []arr = { 1, 2, 3, 2, 1 };
int N = arr.Length;
int K = 3;
// Function Call
Console.WriteLine(maxMedian(arr, N, K));
}
}
// This code is contributed by Samim Hossain Mondal.
JavaScript
<script>
// JavaScript code for the above approach
// Function to find the maximum median
// of a sub array having length at least k.
function maxMedian(arr, N, K)
{
// Variable to keep track
// of maximum median.
let mx_median = -1;
// Go through all the sub arrays
// having length at least K.
for (let i = 0; i < N; i++) {
for (let j = i + K - 1; j < N; j++) {
let len = j - i + 1;
let temp = new Array(len).fill(0)
// Copy all elements of
// arr[i ... j] to temp[].
for (let k = i; k <= j; k++)
temp[k - i] = arr[k];
// Sort the temp[] array
// to find the median.
temp.sort(function (a, b) { return a - b })
let x = Math.floor((len - 1) / 2)
mx_median = Math.max(mx_median,
temp[x]);
}
}
return mx_median;
}
// Driver code
let arr = [1, 2, 3, 2, 1];
let N = arr.length;
let K = 3;
// Function Call
document.write(maxMedian(arr, N, K));
// This code is contributed by Potta Lokesh
</script>
Time Complexity: O(N3 log(N))
Auxiliary Space: O(N)
Efficient Approach: An efficient approach is to use the binary search algorithm. Prefix sum technique can be used here in order to check quickly if there exists any segment of length at least K having a sum greater than zero, it helps in reducing the time complexity. Follow the steps below to solve the given problem.
- Let l and r denote the left and right boundary for our binary search algorithm.
- For each mid-value check if it is possible to have a median equal to mid of a subarray having a length of at least K.
- Define a function for checking the above condition.
- Take an array of length N ( Pre[] ) and at i-th index store 1 if arr[i] >= mid else -1.
- Calculate the prefix sum of the array Pre[].
- Now in some segments, the median is at least x if the sum on this sub-segment is positive. Now we only need to check if the array Pre[] consisting of -1 and 1 has a sub-segment of length at least K with positive-sum.
- For prefix sum at position i choose the minimum prefix sum amongst positions 0, 1, . . ., i-K, which can be done using prefix minimum in linear time.
- Maintain the maximum sum of a sub-array having a length of at least K.
- If the maximum sum is greater than 0 return true, else return false.
- Return the maximum median possible finally.
Below is the implementation of the above approach.
C++
// C++ code to find the maximum median
// of a sub array having length at least K
#include <bits/stdc++.h>
using namespace std;
// Function to check if
// the median is possible or not.
bool good(int arr[], int& N, int& K,
int& median)
{
int pre[N];
for (int i = 0; i < N; i++) {
if (arr[i] >= median)
pre[i] = 1;
else
pre[i] = -1;
if (i > 0)
pre[i] += pre[i - 1];
}
// mx denotes the maximum
// sum of a sub array having
// length at least k.
int mx = pre[K - 1];
// mn denotes the minimum
// prefix sum seen so far.
int mn = 0;
for (int i = K; i < N; i++) {
mn = min(mn, pre[i - K]);
mx = max(mx, pre[i] - mn);
}
if (mx > 0)
return true;
return false;
}
// Function to find the maximum median
// of a sub array having length at least K
int maxMedian(int arr[], int N, int K)
{
// l and r denote the left and right
// boundary for binary search algorithm
int l = 1, r = N + 1;
// Variable to keep track
// of maximum median
int mx_median = -1;
while (l <= r) {
int mid = (l + r) / 2;
if (good(arr, N, K, mid)) {
mx_median = mid;
l = mid + 1;
}
else
r = mid - 1;
}
return mx_median;
}
// Driver function
int main()
{
int arr[] = { 1, 2, 3, 2, 1 };
int N = sizeof(arr) / sizeof(arr[0]);
int K = 3;
// Function Call
cout << maxMedian(arr, N, K);
return 0;
}
Java
// Java code to find the maximum median
// of a sub array having length at least K
import java.util.*;
class GFG{
// Function to check if
// the median is possible or not.
static boolean good(int arr[], int N, int K,
int median)
{
int []pre = new int[N];
for (int i = 0; i < N; i++) {
if (arr[i] >= median)
pre[i] = 1;
else
pre[i] = -1;
if (i > 0)
pre[i] += pre[i - 1];
}
// mx denotes the maximum
// sum of a sub array having
// length at least k.
int mx = pre[K - 1];
// mn denotes the minimum
// prefix sum seen so far.
int mn = 0;
for (int i = K; i < N; i++) {
mn = Math.min(mn, pre[i - K]);
mx = Math.max(mx, pre[i] - mn);
}
if (mx > 0)
return true;
return false;
}
// Function to find the maximum median
// of a sub array having length at least K
static int maxMedian(int arr[], int N, int K)
{
// l and r denote the left and right
// boundary for binary search algorithm
int l = 1, r = N + 1;
// Variable to keep track
// of maximum median
int mx_median = -1;
while (l <= r) {
int mid = (l + r) / 2;
if (good(arr, N, K, mid)) {
mx_median = mid;
l = mid + 1;
}
else
r = mid - 1;
}
return mx_median;
}
// Driver function
public static void main(String[] args)
{
int arr[] = { 1, 2, 3, 2, 1 };
int N = arr.length;
int K = 3;
// Function Call
System.out.print(maxMedian(arr, N, K));
}
}
// This code is contributed by 29AjayKumar
Python
# Python code to find the maximum median
# of a sub array having length at least K
# Function to check if
# the median is possible or not.
def good(arr, N, K, median):
pre = [0]*N
for i in range(N):
if(arr[i] >= median):
pre[i] = 1
else:
pre[i] = -1
if(i > 0):
pre[i] += pre[i-1]
# mx denotes the maximum
# sum of a sub array having
# length at least k.
mx = pre[K-1]
# mn denotes the minimum
# prefix sum seen so far.
mn = 0
for i in range(K, N):
mn = min(mn, pre[i-K])
mx = max(mx, pre[i]-mn)
if(mx > 0):
return True
return False
# Function to find the maximum median
# of a sub array having length at least K
def maxMedian(arr, N, K):
# l and r denote the left and right
# boundary for binary search algorithm
l, r = 1, N+1
# Variable to keep track
# of maximum median
mx_median = -1
while(l <= r):
mid = (l+r)//2
if(good(arr, N, K, mid)):
mx_median = mid
l = mid+1
else:
r = mid-1
return mx_median
arr = [1, 2, 3, 2, 1]
N = len(arr)
K = 3
# Function call
print(maxMedian(arr, N, K))
# This code is contributed by lokeshmvs21.
C#
// C# code to find the maximum median
// of a sub array having length at least K
using System;
public class GFG{
// Function to check if
// the median is possible or not.
static bool good(int []arr, int N, int K,
int median)
{
int []pre = new int[N];
for (int i = 0; i < N; i++) {
if (arr[i] >= median)
pre[i] = 1;
else
pre[i] = -1;
if (i > 0)
pre[i] += pre[i - 1];
}
// mx denotes the maximum
// sum of a sub array having
// length at least k.
int mx = pre[K - 1];
// mn denotes the minimum
// prefix sum seen so far.
int mn = 0;
for (int i = K; i < N; i++) {
mn = Math.Min(mn, pre[i - K]);
mx = Math.Max(mx, pre[i] - mn);
}
if (mx > 0)
return true;
return false;
}
// Function to find the maximum median
// of a sub array having length at least K
static int maxMedian(int []arr, int N, int K)
{
// l and r denote the left and right
// boundary for binary search algorithm
int l = 1, r = N + 1;
// Variable to keep track
// of maximum median
int mx_median = -1;
while (l <= r) {
int mid = (l + r) / 2;
if (good(arr, N, K, mid)) {
mx_median = mid;
l = mid + 1;
}
else
r = mid - 1;
}
return mx_median;
}
// Driver function
public static void Main(String[] args)
{
int []arr = { 1, 2, 3, 2, 1 };
int N = arr.Length;
int K = 3;
// Function Call
Console.Write(maxMedian(arr, N, K));
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// javascript code to find the maximum median
// of a sub array having length at least K
// Function to check if
// the median is possible or not.
function good(arr , N , K,
median)
{
var pre = Array.from({length: N}, (_, i) => 0);
for (var i = 0; i < N; i++) {
if (arr[i] >= median)
pre[i] = 1;
else
pre[i] = -1;
if (i > 0)
pre[i] += pre[i - 1];
}
// mx denotes the maximum
// sum of a sub array having
// length at least k.
var mx = pre[K - 1];
// mn denotes the minimum
// prefix sum seen so far.
var mn = 0;
for (var i = K; i < N; i++) {
mn = Math.min(mn, pre[i - K]);
mx = Math.max(mx, pre[i] - mn);
}
if (mx > 0)
return true;
return false;
}
// Function to find the maximum median
// of a sub array having length at least K
function maxMedian(arr , N , K)
{
// l and r denote the left and right
// boundary for binary search algorithm
var l = 1, r = N + 1;
// Variable to keep track
// of maximum median
var mx_median = -1;
while (l <= r) {
var mid = parseInt((l + r) / 2);
if (good(arr, N, K, mid)) {
mx_median = mid;
l = mid + 1;
}
else
r = mid - 1;
}
return mx_median;
}
// Driver function
var arr = [ 1, 2, 3, 2, 1 ];
var N = arr.length;
var K = 3;
// Function Call
document.write(maxMedian(arr, N, K));
// This code is contributed by shikhasingrajput
</script>
Time Complexity: O(N * logN).
Auxiliary Space: O(N)
Similar Reads
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
What is Binary Search Algorithm? Binary Search is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half and the correct interval to find is decided based on the searched value and the mid value of the interval. Example of binary searchProperties of Binary Search:Binary search is performed o
1 min read
Time and Space Complexity Analysis of Binary Search Algorithm Time complexity of Binary Search is O(log n), where n is the number of elements in the array. It divides the array in half at each step. Space complexity is O(1) as it uses a constant amount of extra space. Example of Binary Search AlgorithmAspectComplexityTime ComplexityO(log n)Space ComplexityO(1)
3 min read
How to calculate "mid" or Middle Element Index in Binary Search? The most common method to calculate mid or middle element index in Binary Search Algorithm is to find the middle of the highest index and lowest index of the searchable space, using the formula mid = low + \frac{(high - low)}{2} Finding the middle index "mid" in Binary Search AlgorithmIs this method
6 min read
Variants of Binary Search
Variants of Binary SearchBinary search is very easy right? Well, binary search can become complex when element duplication occurs in the sorted list of values. It's not always the "contains or not" we search using Binary Search, but there are 5 variants such as below:1) Contains (True or False)Â 2) Index of first occurrence
15+ min read
Meta Binary Search | One-Sided Binary SearchMeta binary search (also called one-sided binary search by Steven Skiena in The Algorithm Design Manual on page 134) is a modified form of binary search that incrementally constructs the index of the target value in the array. Like normal binary search, meta binary search takes O(log n) time. Meta B
9 min read
The Ubiquitous Binary Search | Set 1We are aware of the binary search algorithm. Binary search is the easiest algorithm to get right. I present some interesting problems that I collected on binary search. There were some requests on binary search. I request you to honor the code, "I sincerely attempt to solve the problem and ensure th
15+ min read
Uniform Binary SearchUniform Binary Search is an optimization of Binary Search algorithm when many searches are made on same array or many arrays of same size. In normal binary search, we do arithmetic operations to find the mid points. Here we precompute mid points and fills them in lookup table. The array look-up gene
7 min read
Randomized Binary Search AlgorithmWe are given a sorted array A[] of n elements. We need to find if x is present in A or not.In binary search we always used middle element, here we will randomly pick one element in given range.In Binary Search we had middle = (start + end)/2 In Randomized binary search we do following Generate a ran
13 min read
Abstraction of Binary SearchWhat is the binary search algorithm? Binary Search Algorithm is used to find a certain value of x for which a certain defined function f(x) needs to be maximized or minimized. It is frequently used to search an element in a sorted sequence by repeatedly dividing the search interval into halves. Begi
7 min read
N-Base modified Binary Search algorithmN-Base modified Binary Search is an algorithm based on number bases that can be used to find an element in a sorted array arr[]. This algorithm is an extension of Bitwise binary search and has a similar running time. Examples: Input: arr[] = {1, 4, 5, 8, 11, 15, 21, 45, 70, 100}, target = 45Output:
10 min read
Implementation of Binary Search in different languages
C Program for Binary SearchIn this article, we will understand the binary search algorithm and how to implement binary search programs in C. We will see both iterative and recursive approaches and how binary search can reduce the time complexity of the search operation as compared to linear search.Table of ContentWhat is Bina
7 min read
C++ Program For Binary SearchBinary Search is a popular searching algorithm which is used for finding the position of any given element in a sorted array. It is a type of interval searching algorithm that keep dividing the number of elements to be search into half by considering only the part of the array where there is the pro
5 min read
C Program for Binary SearchIn this article, we will understand the binary search algorithm and how to implement binary search programs in C. We will see both iterative and recursive approaches and how binary search can reduce the time complexity of the search operation as compared to linear search.Table of ContentWhat is Bina
7 min read
Binary Search functions in C++ STL (binary_search, lower_bound and upper_bound)In C++, STL provide various functions like std::binary_search(), std::lower_bound(), and std::upper_bound() which uses the the binary search algorithm for different purposes. These function will only work on the sorted data.There are the 3 binary search function in C++ STL:Table of Contentbinary_sea
3 min read
Binary Search in JavaBinary search is a highly efficient searching algorithm used when the input is sorted. It works by repeatedly dividing the search range in half, reducing the number of comparisons needed compared to a linear search. Here, we are focusing on finding the middle element that acts as a reference frame t
6 min read
Binary Search (Recursive and Iterative) - PythonBinary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Below is the step-by-step algorithm for Binary Search:D
6 min read
Binary Search In JavaScriptBinary Search is a searching technique that works on the Divide and Conquer approach. It is used to search for any element in a sorted array. Compared with linear, binary search is much faster with a Time Complexity of O(logN), whereas linear search works in O(N) time complexityExamples: Input : arr
3 min read
Binary Search using pthreadBinary search is a popular method of searching in a sorted array or list. It simply divides the list into two halves and discards the half which has zero probability of having the key. On dividing, we check the midpoint for the key and use the lower half if the key is less than the midpoint and the
8 min read
Comparison with other Searching
Binary Search Intuition and Predicate Functions The binary search algorithm is used in many coding problems, and it is usually not very obvious at first sight. However, there is certainly an intuition and specific conditions that may hint at using binary search. In this article, we try to develop an intuition for binary search. Introduction to Bi
12 min read
Can Binary Search be applied in an Unsorted Array? Binary Search is a search algorithm that is specifically designed for searching in sorted data structures. This searching algorithm is much more efficient than Linear Search as they repeatedly target the center of the search structure and divide the search space in half. It has logarithmic time comp
9 min read
Find a String in given Array of Strings using Binary Search Given a sorted array of Strings arr and a string x, The task is to find the index of x in the array using the Binary Search algorithm. If x is not present, return -1.Examples:Input: arr[] = {"contribute", "geeks", "ide", "practice"}, x = "ide"Output: 2Explanation: The String x is present at index 2.
6 min read