Given an array arr[0..n-1] of n integers, find the maximum length subarray such that its first element is greater than or equal to the last element of the subarray.
Examples:
Input : arr[] = {-5, -1, 7, 5, 1, -2}
Output : 5
Explanation : Subarray {-1, 7, 5, 1, -2} forms maximum
length subarray with its first element greater than last.
Input : arr[] = {1, 5, 7}
Output : 1
Naive approach is to use two nested loops for every possible starting and ending element of the subarray and if it satisfies the condition then update the answer accordingly.
Time Complexity : O(n^2)
A Better approach is to use Binary search. In this approach for each element in the array we maximise the length of the subarray ending at that element. Then we take the maximum of the all the lengths.
We will take another array which is used as our search space for choosing the starting element of. We will keep adding element in it as we traverse the array if the element is greater than all the previous elements present in the search space.
The key observation here is that we will add an element to our search space only when it is greater than all the element of the search space because if the element is lower any other element then it can never be chosen as the first element of the maximum length subarray since we would have a better choice.
Since the search space is always sorted in increasing order, we just need compare the current element of the array with last element of the search space and if and only if its greater than the last element we add it to the search space otherwise not.
Below is the implementation of the above approach
C++
#include <algorithm>
#include <iostream>
using namespace std;
int binarySearch( int * searchSpace, int s, int e, int num)
{
int ans;
while (s <= e) {
int mid = (s + e) / 2;
if (searchSpace[mid] >= num) {
ans = mid;
e = mid - 1;
}
else
s = mid + 1;
}
return ans;
}
int longestSubArr( int * arr, int n)
{
int searchSpace[n];
int index[n];
int j = 0;
int ans = 0;
for ( int i = 0; i < n; ++i) {
if (j == 0 or searchSpace[j - 1] < arr[i]) {
searchSpace[j] = arr[i];
index[j] = i;
j++;
}
int idx = binarySearch(searchSpace, 0, j - 1, arr[i]);
ans = max(ans, i - index[idx] + 1);
}
return ans;
}
int main( int argc, char const * argv[])
{
int arr[] = { -5, -1, 7, 5, 1, -2 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << longestSubArr(arr, n) << endl;
return 0;
}
|
Java
class GFG
{
static int binarySearch( int []searchSpace, int s,
int e, int num)
{
int ans = 0 ;
while (s <= e)
{
int mid = (s + e) / 2 ;
if (searchSpace[mid] >= num)
{
ans = mid;
e = mid - 1 ;
}
else
s = mid + 1 ;
}
return ans;
}
static int longestSubArr( int []arr, int n)
{
int []searchSpace = new int [n];
int []index = new int [n];
int j = 0 ;
int ans = 0 ;
for ( int i = 0 ; i < n; ++i)
{
if (j == 0 || searchSpace[j - 1 ] < arr[i])
{
searchSpace[j] = arr[i];
index[j] = i;
j++;
}
int idx = binarySearch(searchSpace, 0 ,
j - 1 , arr[i]);
ans = Math.max(ans, i - index[idx] + 1 );
}
return ans;
}
public static void main(String[] args)
{
int arr[] = { - 5 , - 1 , 7 , 5 , 1 , - 2 };
int n = arr.length;
System.out.println(longestSubArr(arr, n));
}
}
|
Python3
def binarySearch(searchSpace, s, e, num):
while (s < = e):
mid = (s + e) / / 2
if searchSpace[mid] > = num :
ans = mid
e = mid - 1
else :
s = mid + 1
return ans
def longestSubArr(arr, n):
searchSpace = [ None ] * n
index = [ None ] * n
j = 0
ans = 0
for i in range (n):
if (j = = 0 or searchSpace[j - 1 ] < arr[i]) :
searchSpace[j] = arr[i]
index[j] = i
j + = 1
idx = binarySearch(searchSpace, 0 ,
j - 1 , arr[i])
ans = max (ans, i - index[idx] + 1 )
return ans
if __name__ = = "__main__" :
arr = [ - 5 , - 1 , 7 , 5 , 1 , - 2 ]
n = len (arr)
print (longestSubArr(arr, n))
|
C#
using System;
class GFG
{
static int binarySearch( int [] searchSpace,
int s, int e, int num)
{
int ans = 0;
while (s <= e)
{
int mid = (s + e) / 2;
if (searchSpace[mid] >= num)
{
ans = mid;
e = mid - 1;
}
else
s = mid + 1;
}
return ans;
}
static int longestSubArr( int [] arr, int n)
{
int [] searchSpace = new int [n];
int [] index = new int [n];
int j = 0;
int ans = 0;
for ( int i = 0; i < n; ++i)
{
if (j == 0 || searchSpace[j - 1] < arr[i])
{
searchSpace[j] = arr[i];
index[j] = i;
j++;
}
int idx = binarySearch(searchSpace, 0,
j - 1, arr[i]);
ans = Math.Max(ans, i - index[idx] + 1);
}
return ans;
}
public static void Main()
{
int [] arr = { -5, -1, 7, 5, 1, -2 };
int n = arr.Length;
Console.Write(longestSubArr(arr, n));
}
}
|
PHP
<?php
function binarySearch( $searchSpace ,
$s , $e , $num )
{
$ans = 0;
while ( $s <= $e )
{
$mid = ( $s + $e ) / 2;
if ( $searchSpace [ $mid ] >= $num )
{
$ans = $mid ;
$e = $mid - 1;
}
else
{
$s = $mid + 1;
}
}
return $ans ;
}
function longestSubArr(& $arr , $n )
{
$j = 0;
$ans = 0;
for ( $i = 0; $i < $n ; ++ $i )
{
if ( $j == 0 or
$searchSpace [ $j - 1] < $arr [ $i ])
{
$searchSpace [ $j ] = $arr [ $i ];
$index [ $j ] = $i ;
$j ++;
}
$idx = binarySearch( $searchSpace , 0,
$j - 1, $arr [ $i ]);
$ans = max( $ans , $i - $index [ $idx ] + 1);
}
return $ans ;
}
$arr = array (-5, -1, 7, 5, 1, -2);
$n = sizeof( $arr );
echo (longestSubArr( $arr , $n )) ;
?>
|
Javascript
<script>
function binarySearch(searchSpace, s, e, num)
{
let ans = 0;
while (s <= e)
{
let mid = Math.floor((s + e) / 2);
if (searchSpace[mid] >= num)
{
ans = mid;
e = mid - 1;
}
else
s = mid + 1;
}
return ans;
}
function longestSubArr(arr, n)
{
let searchSpace = new Array(n);
let index = new Array(n);
let j = 0;
let ans = 0;
for (let i = 0; i < n; ++i)
{
if (j == 0 || searchSpace[j - 1] < arr[i])
{
searchSpace[j] = arr[i];
index[j] = i;
j++;
}
let idx = binarySearch(searchSpace, 0,
j - 1, arr[i]);
ans = Math.max(ans, i - index[idx] + 1);
}
return ans;
}
let arr = [ -5, -1, 7, 5, 1, -2 ];
let n = arr.length;
document.write(longestSubArr(arr, n));
</script>
|
Time Complexity : (N * log N)
Binary search function takes Log N time and the it will be called N times.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
30 Aug, 2022
Like Article
Save Article