Skip to content
Related Articles

Related Articles

Improve Article

Longest Subarray with first element greater than or equal to Last element

  • Difficulty Level : Hard
  • Last Updated : 12 May, 2021

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++




// CPP program to find length of the longest
// array with first element smaller than or
// equal to last element.
#include <algorithm>
#include <iostream>
using namespace std;
 
// Search function for searching the first element of the
// subarray which is greater or equal to the last element(num)
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;
}
 
// Returns length of the longest array with first
// element smaller than the last element.
int longestSubArr(int* arr, int n)
{
    // Search space for the potential first elements.
    int searchSpace[n];
 
    // It will store the Indexes of the elements
    // of search space in the original array.
    int index[n];
 
    // Initially the search space is empty.
    int j = 0;
    int ans = 0;
 
    for (int i = 0; i < n; ++i) {
 
        // We will add an ith element in the search
        // space if the search space is empty or if
        // the ith element is greater than the last
        // element of the search space.
        if (j == 0 or searchSpace[j - 1] < arr[i]) {
            searchSpace[j] = arr[i];
            index[j] = i;
            j++;
        }
 
        // we will search for the index first element in the
        // search space and we will use it find the
        // index of it in the original array.
        int idx = binarySearch(searchSpace, 0, j - 1, arr[i]);
 
        // Update the answer if the length of the subarray is
        // greater than the previously calculated lengths.
        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




// Java program to find length
// of the longest array with
// first element smaller than
// or equal to last element.
class GFG
{
 
// Search function for searching
// the first element of the
// subarray which is greater or
// equal to the last element(num)
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;
}
 
// Returns length of the longest
// array with first element smaller
// than the last element.
static int longestSubArr(int []arr, int n)
{
// Search space for the
// potential first elements.
int []searchSpace = new int[n];
 
// It will store the Indexes
// of the elements of search
// space in the original array.
int []index = new int[n];
 
// Initially the search
// space is empty.
int j = 0;
int ans = 0;
 
for (int i = 0; i < n; ++i)
{
 
    // We will add an ith element
    // in the search space if the
    // search space is empty or if
    // the ith element is greater
    // than the last element of
    // the search space.
    if (j == 0 || searchSpace[j - 1] < arr[i])
    {
        searchSpace[j] = arr[i];
        index[j] = i;
        j++;
    }
 
    // we will search for the index
    // first element in the search
    // space and we will use it find
    // the index of it in the original array.
    int idx = binarySearch(searchSpace, 0,
                           j - 1, arr[i]);
 
    // Update the answer if the
    // length of the subarray is
    // greater than the previously
    // calculated lengths.
    ans = Math.max(ans, i - index[idx] + 1);
}
return ans;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { -5, -1, 7, 5, 1, -2 };
    int n = arr.length;
    System.out.println(longestSubArr(arr, n));
}
}
 
// This code is contributed
// by ChitraNayal

Python3




# Python 3 program to find
# length of the longest array
# with first element smaller
# than or equal to last element.
 
# Search function for searching
# the first element of the
# subarray which is greater or
# equal to the last element(num)
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
 
# Returns length of the longest
# array with first element
# smaller than the last element.
def longestSubArr(arr, n):
 
    # Search space for the
    # potential first elements.
    searchSpace = [None] * n
 
    # It will store the Indexes
    # of the elements of search
    # space in the original array.
    index = [None] * n
 
    # Initially the search
    # space is empty.
    j = 0
    ans = 0
 
    for i in range(n):
 
        # We will add an ith element
        # in the search space if the
        # search space is empty or if
        # the ith element is greater
        # than the last element of
        # the search space.
        if (j == 0 or searchSpace[j - 1] < arr[i]) :
            searchSpace[j] = arr[i]
            index[j] = i
            j += 1
 
        # we will search for the index
        # first element in the search
        # space and we will use it
        # find the index of it in the
        # original array.
        idx = binarySearch(searchSpace, 0,
                           j - 1, arr[i])
 
        # Update the answer if the length
        # of the subarray is greater than
        # the previously calculated lengths.
        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))
 
# This code is contributed
# by ChitraNayal

C#




// C# program to find length
// of the longest array with
// first element smaller than
// or equal to last element.
using System;
 
class GFG
{
 
// Search function for searching
// the first element of the
// subarray which is greater or
// equal to the last element(num)
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;
}
 
// Returns length of the longest
// array with first element smaller
// than the last element.
static int longestSubArr(int[] arr, int n)
{
     
// Search space for the
// potential first elements.
int[] searchSpace = new int[n];
 
// It will store the Indexes
// of the elements of search
// space in the original array.
int[] index = new int[n];
 
// Initially the search
// space is empty.
int j = 0;
int ans = 0;
 
for (int i = 0; i < n; ++i)
{
 
    // We will add an ith element
    // in the search space if the
    // search space is empty or if
    // the ith element is greater
    // than the last element of
    // the search space.
    if (j == 0 || searchSpace[j - 1] < arr[i])
    {
        searchSpace[j] = arr[i];
        index[j] = i;
        j++;
    }
 
    // we will search for the index
    // first element in the search
    // space and we will use it find the
    // index of it in the original array.
    int idx = binarySearch(searchSpace, 0,
                           j - 1, arr[i]);
 
    // Update the answer if the
    // length of the subarray is
    // greater than the previously
    // calculated lengths.
    ans = Math.Max(ans, i - index[idx] + 1);
}
return ans;
}
 
// Driver code
public static void Main()
{
    int[] arr = { -5, -1, 7, 5, 1, -2 };
    int n = arr.Length;
    Console.Write(longestSubArr(arr, n));
}
}
 
// This code is contributed
// by ChitraNayal

PHP




<?php
// PHP program to find length
// of the longest array with
// first element smaller than
// or equal to last element.
 
 
// Search function for searching
// the first element of the
// subarray which is greater or
// equal to the last element(num)
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;
}
 
// Returns length of the longest
// array with first element smaller
// than the last element.
function longestSubArr(&$arr, $n)
{
    // Search space for the
    // potential first elements.
 
    // It will store the Indexes
    // of the elements of search
    // space in the original array.
     
    // Initially the search
    // space is empty.
    $j = 0;
    $ans = 0;
    for ($i = 0; $i < $n; ++$i)
    {
 
        // We will add an ith element
        // in the search space if the
        // search space is empty or if
        // the ith element is greater
        // than the last element of the
        // search space.
        if ($j == 0 or
            $searchSpace[$j - 1] < $arr[$i])
        {
            $searchSpace[$j] = $arr[$i];
            $index[$j] = $i;
            $j++;
        }
     
 
        // we will search for the index
        // first element in the search
        // space and we will use it find
        // the index of it in the original
        // array.
        $idx = binarySearch($searchSpace, 0,
                            $j - 1, $arr[$i]);
 
        // Update the answer if the length
        // of the subarray is greater than
        // the previously calculated lengths.
        $ans = max($ans, $i - $index[$idx] + 1);
    }
    return $ans;
}
 
// Driver code
$arr = array(-5, -1, 7, 5, 1, -2);
$n = sizeof($arr);
echo (longestSubArr($arr, $n)) ;
 
// This code is contributed
// by Shivi_Aggarwal
?>

Javascript




<script>
 
// Javascript program to find length
// of the longest array with
// first element smaller than
// or equal to last element.
 
// Search function for searching
// the first element of the
// subarray which is greater or
// equal to the last element(num)
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;
}
 
// Returns length of the longest
// array with first element smaller
// than the last element.
function longestSubArr(arr, n)
{
     
    // Search space for the
    // potential first elements.
    let searchSpace = new Array(n);
       
    // It will store the Indexes
    // of the elements of search
    // space in the original array.
    let index = new Array(n);
       
    // Initially the search
    // space is empty.
    let j = 0;
    let ans = 0;
       
    for(let i = 0; i < n; ++i)
    {
         
        // We will add an ith element
        // in the search space if the
        // search space is empty or if
        // the ith element is greater
        // than the last element of
        // the search space.
        if (j == 0 || searchSpace[j - 1] < arr[i])
        {
            searchSpace[j] = arr[i];
            index[j] = i;
            j++;
        }
       
        // We will search for the index
        // first element in the search
        // space and we will use it find
        // the index of it in the original array.
        let idx = binarySearch(searchSpace, 0,
                               j - 1, arr[i]);
       
        // Update the answer if the
        // length of the subarray is
        // greater than the previously
        // calculated lengths.
        ans = Math.max(ans, i - index[idx] + 1);
    }
    return ans;   
}
 
// Driver code
let arr = [ -5, -1, 7, 5, 1, -2 ];
let n = arr.length;
 
document.write(longestSubArr(arr, n));
 
// This code is contributed by avanitrachhadiya2155
 
</script>

Output 

5

Time Complexity – (N * log N) 
Binary search function takes Log N time and the it will be called N times.
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :