Given an array arr[], find the maximum j – i such that arr[j] > arr[i]

Given an array arr[], find the maximum j – i such that arr[j] > arr[i].
Examples : 

  Input: {34, 8, 10, 3, 2, 80, 30, 33, 1}
  Output: 6  (j = 7, i = 1)

  Input: {9, 2, 3, 4, 5, 6, 7, 8, 18, 0}
  Output: 8 ( j = 8, i = 0)

  Input:  {1, 2, 3, 4, 5, 6}
  Output: 5  (j = 5, i = 0)

  Input:  {6, 5, 4, 3, 2, 1}
  Output: -1 

Method 1 (Simple but Inefficient) 
Run two loops. In the outer loop, pick elements one by one from left. In the inner loop, compare the picked element with the elements starting from the right side. Stop the inner loop when you see an element greater than the picked element and keep updating the maximum j-i so far. 
 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <bits/stdc++.h>
 
using namespace std;
/* For a given array arr[], returns the maximum j – i such that
    arr[j] > arr[i] */
int maxIndexDiff(int arr[], int n)
{
    int maxDiff = -1;
    int i, j;
 
    for (i = 0; i < n; ++i) {
        for (j = n - 1; j > i; --j) {
            if (arr[j] > arr[i] && maxDiff < (j - i))
                maxDiff = j - i;
        }
    }
 
    return maxDiff;
}
 
int main()
{
    int arr[] = { 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int maxDiff = maxIndexDiff(arr, n);
    cout << "\n"
         << maxDiff;
    return 0;
}
 
// This code is contributed
// by Akanksha Rai(Abby_akku)

chevron_right


C

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <stdio.h>
/* For a given array arr[], returns the maximum j – i such that
    arr[j] > arr[i] */
int maxIndexDiff(int arr[], int n)
{
    int maxDiff = -1;
    int i, j;
 
    for (i = 0; i < n; ++i) {
        for (j = n - 1; j > i; --j) {
            if (arr[j] > arr[i] && maxDiff < (j - i))
                maxDiff = j - i;
        }
    }
 
    return maxDiff;
}
 
int main()
{
    int arr[] = { 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int maxDiff = maxIndexDiff(arr, n);
    printf("\n %d", maxDiff);
    getchar();
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

class FindMaximum {
    /* For a given array arr[], returns the maximum j-i such that
       arr[j] > arr[i] */
    int maxIndexDiff(int arr[], int n)
    {
        int maxDiff = -1;
        int i, j;
 
        for (i = 0; i < n; ++i) {
            for (j = n - 1; j > i; --j) {
                if (arr[j] > arr[i] && maxDiff < (j - i))
                    maxDiff = j - i;
            }
        }
 
        return maxDiff;
    }
 
    /* Driver program to test above functions */
    public static void main(String[] args)
    {
        FindMaximum max = new FindMaximum();
        int arr[] = { 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 };
        int n = arr.length;
        int maxDiff = max.maxIndexDiff(arr, n);
        System.out.println(maxDiff);
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find the maximum
# j – i such that arr[j] > arr[i]
  
# For a given array arr[], returns
# the maximum j – i such that
# arr[j] > arr[i]
def maxIndexDiff(arr, n):
    maxDiff = -1
    for i in range(0, n):
        j = n - 1
        while(j > i):
            if arr[j] > arr[i] and maxDiff < (j - i):
                maxDiff = j - i;
            j -= 1
     
    return maxDiff
 
# driver code
arr = [9, 2, 3, 4, 5, 6, 7, 8, 18, 0]
n = len(arr)
maxDiff = maxIndexDiff(arr, n)
print(maxDiff)
 
# This article is contributed by Smitha Dinesh Semwal

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find the maximum
// j – i such that arr[j] > arr[i]
using System;
class GFG {
    // For a given array arr[], returns
    // the maximum j-i such that arr[j] > arr[i]
    static int maxIndexDiff(int[] arr, int n)
    {
        int maxDiff = -1;
        int i, j;
 
        for (i = 0; i < n; ++i) {
            for (j = n - 1; j > i; --j) {
                if (arr[j] > arr[i] && maxDiff < (j - i))
                    maxDiff = j - i;
            }
        }
 
        return maxDiff;
    }
 
    // Driver program
    public static void Main()
    {
 
        int[] arr = { 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 };
        int n = arr.Length;
        int maxDiff = maxIndexDiff(arr, n);
        Console.Write(maxDiff);
    }
}
// This Code is Contributed by Sam007

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to find the maximum
// j – i such that arr[j] > arr[i]
 
// For a given array arr[], returns
// the maximum j – i such that
// arr[j] > arr[i]
function maxIndexDiff($arr, $n)
{
    $maxDiff = -1;
     
    for ($i = 0; $i < $n; ++$i)
    {
        for ($j = $n - 1; $j > $i; --$j)
        {
            if($arr[$j] > $arr[$i] &&
               $maxDiff < ($j - $i))
                $maxDiff = $j - $i;
        }
    }
 
    return $maxDiff;
}
 
// Driver Code
$arr = array(9, 2, 3, 4, 5,
             6, 7, 8, 18, 0);
$n = count($arr);
$maxDiff = maxIndexDiff($arr, $n);
echo $maxDiff ;
 
// This code is contributed by Sam007
?>

chevron_right


Output: 

8










 

Time Complexity: O(n^2)
Method 2 – 
Improvising the Brute Force Algorithm and looking for BUD, i.e Bottlenecks, unnecessary and duplicated works. A quick observation actually shows that we have been looking to find the first greatest element traversing from the end of the array to the current index. We can see that we are trying to find the first greatest element again and again for each element in the array. Let’s say we have an array with us for example [1, 5, 12, 4, 9] now we know that 9 is the element which is greater than 1, 5, and 4 but why do we need to find that again and again. We can actually keep a track of the maximum number moving from the end to the start of the array. The approach will help us understand better and also this improvisation is great to come up within an interview. 
Approach :  

  1. Traverse the array from the end and keep a track of the maximum number to the right of the current index including self
  2. Now we have a monotonous decreasing array, and we know we can use binary search to find the index of the rightmost greater element
  3. Now we will just use binary search for each of the elements in the array and store the maximum difference of the indices and that’s it we are done.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

/* For a given array arr[], calculates the maximum j – i such that
    arr[j] > arr[i] */
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    vector<long long int> v{ 34, 8, 10, 3, 2, 80, 30, 33, 1 };
    int n = v.size();
    vector<long long int> maxFromEnd(n + 1, INT_MIN);
 
    // create an array maxfromEnd
    for (int i = v.size() - 1; i >= 0; i--) {
        maxFromEnd[i] = max(maxFromEnd[i + 1], v[i]);
    }
 
    int result = 0;
 
    for (int i = 0; i < v.size(); i++) {
        int low = i + 1, high = v.size() - 1, ans = i;
 
        while (low <= high) {
            int mid = (low + high) / 2;
 
            if (v[i] <= maxFromEnd[mid]) {
                // we store this as current answer and look
                // for further larger number to the right side
                ans = max(ans, mid);
                low = mid + 1;
            }
            else {
                high = mid - 1;
            }
        }
        // keeping a track of the
        // maximum difference in indices
        result = max(result, ans - i);
    }
    cout << result << endl;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above approach
 
// For a given array arr[],
// calculates the maximum j – i
// such that arr[j] > arr[i]
import java.util.*;
class GFG{
 
public static void main(String[] args)
{
  int []v = {34, 8, 10, 3, 2,
             80, 30, 33, 1};
  int n = v.length;
  int []maxFromEnd = new int[n + 1];
  Arrays.fill(maxFromEnd, Integer.MIN_VALUE);
 
  // Create an array maxfromEnd
  for (int i = v.length - 1; i >= 0; i--)
  {
    maxFromEnd[i] = Math.max(maxFromEnd[i + 1],
                             v[i]);
  }
 
  int result = 0;
 
  for (int i = 0; i < v.length; i++)
  {
    int low = i + 1, high = v.length - 1,
        ans = i;
 
    while (low <= high)
    {
      int mid = (low + high) / 2;
 
      if (v[i] <= maxFromEnd[mid])
      {
        // We store this as current
        // answer and look for further
        // larger number to the right side
        ans = Math.max(ans, mid);
        low = mid + 1;
      }
      else
      {
        high = mid - 1;
      }
    }
     
    // Keeping a track of the
    // maximum difference in indices
    result = Math.max(result, ans - i);
  }
  System.out.print(result + "\n");
}
}
 
// This code is contributed by shikhasingrajput

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above approach
 
# For a given array arr,
# calculates the maximum j – i
# such that arr[j] > arr[i]
 
# Driver code
if __name__ == '__main__':
   
    v = [34, 8, 10, 3,
         2, 80, 30, 33, 1];
    n = len(v);
    maxFromEnd = [-38749432] * (n + 1);
 
    # Create an array maxfromEnd
    for i in range(n - 1, 0, -1):
        maxFromEnd[i] = max(maxFromEnd[i + 1],
                            v[i]);
 
    result = 0;
 
    for i in range(0, n):
        low = i + 1; high = n - 1; ans = i;
 
        while (low <= high):
            mid = int((low + high) / 2);
 
            if (v[i] <= maxFromEnd[mid]):
               
                # We store this as current
                # answer and look for further
                # larger number to the right side
                ans = max(ans, mid);
                low = mid + 1;
            else:
                high = mid - 1;       
 
        # Keeping a track of the
        # maximum difference in indices
        result = max(result, ans - i);
     
    print(result, end = "");
     
# This code is contributed by Rajput-Ji

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
 
// For a given array []arr,
// calculates the maximum j – i
// such that arr[j] > arr[i]
using System;
class GFG{
 
public static void Main(String[] args)
{
  int []v = {34, 8, 10, 3, 2,
             80, 30, 33, 1};
  int n = v.Length;
  int []maxFromEnd = new int[n + 1];
   
  for (int i = 0;
           i < maxFromEnd.Length; i++)
    maxFromEnd[i] = int.MinValue;
 
  // Create an array maxfromEnd
  for (int i = v.Length - 1;
           i >= 0; i--)
  {
    maxFromEnd[i] = Math.Max(maxFromEnd[i + 1],
                             v[i]);
  }
 
  int result = 0;
 
  for (int i = 0; i < v.Length; i++)
  {
    int low = i + 1,
        high = v.Length - 1,
    ans = i;
 
    while (low <= high)
    {
      int mid = (low + high) / 2;
 
      if (v[i] <= maxFromEnd[mid])
      {
        // We store this as current
        // answer and look for further
        // larger number to the right side
        ans = Math.Max(ans, mid);
        low = mid + 1;
      }
      else
      {
        high = mid - 1;
      }
    }
 
    // Keeping a track of the
    // maximum difference in indices
    result = Math.Max(result, ans - i);
  }
  Console.Write(result + "\n");
}
}
 
// This code is contributed by shikhasingrajput

chevron_right


Output: 



6










 

Time complexity : O(N*log(N)) 
Space complexity : O(N)
Method 3 O(nLgn) 
Use hashing and sorting to solve this problem in less than quadratic complexity after taking special care of the duplicates. 
Approach :  

  1. Traverse the array and store the index of each element in a list (to handle duplicates).
  2. Sort the array.
  3. Now traverse the array and keep track of the maximum difference of i and j.
  4. For j consider the last index from the list of possible index of the element and for i consider the first index from the list. (As the index were appended in ascending order).
  5. Keep updating the max difference till the end of the array.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the above approach
n = 9
a = [34, 8, 10, 3, 2, 80, 30, 33, 1]
 
# To store the index of an element.
index = dict()
for i in range(n):
    if a[i] in index:
 
        # append to list (for duplicates)
        index[a[i]].append(i) 
    else:
 
        # if first occurrence
        index[a[i]] = [i]  
 
# sort the input array
a.sort()    
maxDiff = 0
 
# Temporary variable to keep track of minimum i
temp = n    
for i in range(n):
    if temp > index[a[i]][0]:
        temp = index[a[i]][0]
    maxDiff = max(maxDiff, index[a[i]][-1]-temp)
 
print(maxDiff)

chevron_right


Output: 

6










 

Time complexity : O(N*log(N)) 
Method 4 (Efficient) 
To solve this problem, we need to get two optimum indexes of arr[]: left index i and right index j. For an element arr[i], we do not need to consider arr[i] for left index if there is an element smaller than arr[i] on left side of arr[i]. Similarly, if there is a greater element on right side of arr[j] then we do not need to consider this j for right index. So we construct two auxiliary arrays LMin[] and RMax[] such that LMin[i] holds the smallest element on left side of arr[i] including arr[i], and RMax[j] holds the greatest element on right side of arr[j] including arr[j]. After constructing these two auxiliary arrays, we traverse both of these arrays from left to right. While traversing LMin[] and RMa[] if we see that LMin[i] is greater than RMax[j], then we must move ahead in LMin[] (or do i++) because all elements on left of LMin[i] are greater than or equal to LMin[i]. Otherwise we must move ahead in RMax[j] to look for a greater j – i value.
Thanks to celicom for suggesting the algorithm for this method. 
 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <bits/stdc++.h>
using namespace std;
 
/* For a given array arr[], 
   returns the maximum j – i such that
   arr[j] > arr[i] */
int maxIndexDiff(int arr[], int n)
{
    int maxDiff;
    int i, j;
 
    int* LMin = new int[(sizeof(int) * n)];
    int* RMax = new int[(sizeof(int) * n)];
 
    /* Construct LMin[] such that
    LMin[i] stores the minimum value
    from (arr[0], arr[1], ... arr[i]) */
    LMin[0] = arr[0];
    for (i = 1; i < n; ++i)
        LMin[i] = min(arr[i], LMin[i - 1]);
 
    /* Construct RMax[] such that
    RMax[j] stores the maximum value from
    (arr[j], arr[j+1], ..arr[n-1]) */
    RMax[n - 1] = arr[n - 1];
    for (j = n - 2; j >= 0; --j)
        RMax[j] = max(arr[j], RMax[j + 1]);
 
    /* Traverse both arrays from left to right
    to find optimum j - i. This process is similar to
    merge() of MergeSort */
    i = 0, j = 0, maxDiff = -1;
    while (j < n && i < n) {
        if (LMin[i] < RMax[j]) {
            maxDiff = max(maxDiff, j - i);
            j = j + 1;
        }
        else
            i = i + 1;
    }
 
    return maxDiff;
}
 
// Driver Code
int main()
{
    int arr[] = { 9, 2, 3, 4, 5,
                  6, 7, 8, 18, 0 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int maxDiff = maxIndexDiff(arr, n);
    cout << maxDiff;
    return 0;
}
 
// This code is contributed by rathbhupendra

chevron_right


C

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <stdio.h>
 
/* Utility Functions to get max and minimum of two integers */
int max(int x, int y)
{
    return x > y ? x : y;
}
 
int min(int x, int y)
{
    return x < y ? x : y;
}
 
/* For a given array arr[], returns the maximum j – i such that
    arr[j] > arr[i] */
int maxIndexDiff(int arr[], int n)
{
    int maxDiff;
    int i, j;
 
    int* LMin = (int*)malloc(sizeof(int) * n);
    int* RMax = (int*)malloc(sizeof(int) * n);
 
    /* Construct LMin[] such that LMin[i] stores the minimum value
       from (arr[0], arr[1], ... arr[i]) */
    LMin[0] = arr[0];
    for (i = 1; i < n; ++i)
        LMin[i] = min(arr[i], LMin[i - 1]);
 
    /* Construct RMax[] such that RMax[j] stores the maximum value
       from (arr[j], arr[j+1], ..arr[n-1]) */
    RMax[n - 1] = arr[n - 1];
    for (j = n - 2; j >= 0; --j)
        RMax[j] = max(arr[j], RMax[j + 1]);
 
    /* Traverse both arrays from left to right to find optimum j - i
        This process is similar to merge() of MergeSort */
    i = 0, j = 0, maxDiff = -1;
    while (j < n && i < n) {
        if (LMin[i] < RMax[j]) {
            maxDiff = max(maxDiff, j - i);
            j = j + 1;
        }
        else
            i = i + 1;
    }
 
    return maxDiff;
}
 
/* Driver program to test above functions */
int main()
{
    int arr[] = { 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int maxDiff = maxIndexDiff(arr, n);
    printf("\n %d", maxDiff);
    getchar();
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

class FindMaximum {
    /* Utility Functions to get max and minimum of two integers */
    int max(int x, int y)
    {
        return x > y ? x : y;
    }
 
    int min(int x, int y)
    {
        return x < y ? x : y;
    }
 
    /* For a given array arr[], returns the maximum j-i such that
       arr[j] > arr[i] */
    int maxIndexDiff(int arr[], int n)
    {
        int maxDiff;
        int i, j;
 
        int RMax[] = new int[n];
        int LMin[] = new int[n];
 
        /* Construct LMin[] such that LMin[i] stores the minimum value
           from (arr[0], arr[1], ... arr[i]) */
        LMin[0] = arr[0];
        for (i = 1; i < n; ++i)
            LMin[i] = min(arr[i], LMin[i - 1]);
 
        /* Construct RMax[] such that RMax[j] stores the maximum value
           from (arr[j], arr[j+1], ..arr[n-1]) */
        RMax[n - 1] = arr[n - 1];
        for (j = n - 2; j >= 0; --j)
            RMax[j] = max(arr[j], RMax[j + 1]);
 
        /* Traverse both arrays from left to right to find optimum j - i
           This process is similar to merge() of MergeSort */
        i = 0;
        j = 0;
        maxDiff = -1;
        while (j < n && i < n) {
            if (LMin[i] < RMax[j]) {
                maxDiff = max(maxDiff, j - i);
                j = j + 1;
            }
            else
                i = i + 1;
        }
 
        return maxDiff;
    }
 
    /* Driver program to test the above functions */
    public static void main(String[] args)
    {
        FindMaximum max = new FindMaximum();
        int arr[] = { 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 };
        int n = arr.length;
        int maxDiff = max.maxIndexDiff(arr, n);
        System.out.println(maxDiff);
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Utility Functions to get max
# and minimum of two integers
def max(a, b):
    if(a > b):
        return a
    else:
        return b
 
def min(a, b):
    if(a < b):
        return a
    else:
        return b
 
# For a given array arr[],
# returns the maximum j - i
# such that arr[j] > arr[i]
def maxIndexDiff(arr, n):
    maxDiff = 0;
    LMin = [0] * n
    RMax = [0] * n
 
    # Construct LMin[] such that
    # LMin[i] stores the minimum
    # value from (arr[0], arr[1],
    # ... arr[i])
    LMin[0] = arr[0]
    for i in range(1, n):
        LMin[i] = min(arr[i], LMin[i - 1])
 
    # Construct RMax[] such that
    # RMax[j] stores the maximum
    # value from (arr[j], arr[j + 1],
    # ..arr[n-1])
    RMax[n - 1] = arr[n - 1]
    for j in range(n - 2, -1, -1):
        RMax[j] = max(arr[j], RMax[j + 1]);
 
    # Traverse both arrays from left
    # to right to find optimum j - i
    # This process is similar to
    # merge() of MergeSort
    i, j = 0, 0
    maxDiff = -1
    while (j < n and i < n):
        if (LMin[i] < RMax[j]):
            maxDiff = max(maxDiff, j - i)
            j = j + 1
        else:
            i = i + 1
 
    return maxDiff
 
# Driver Code
if(__name__ == '__main__'):
    arr = [9, 2, 3, 4, 5,
           6, 7, 8, 18, 0]
    n = len(arr)
    maxDiff = maxIndexDiff(arr, n)
    print (maxDiff)
 
# This code is contributed
# by gautam karakoti

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find the maximum
// j – i such that arr[j] > arr[i]
using System;
 
class GFG {
    // Utility Functions to get max
    // and minimum of two integers
    static int max(int x, int y)
    {
        return x > y ? x : y;
    }
 
    static int min(int x, int y)
    {
        return x < y ? x : y;
    }
 
    // For a given array arr[], returns
    // the maximum j-i such thatarr[j] > arr[i]
    static int maxIndexDiff(int[] arr, int n)
    {
        int maxDiff;
        int i, j;
 
        int[] RMax = new int[n];
        int[] LMin = new int[n];
 
        // Construct LMin[] such that LMin[i]
        // stores the minimum value
        // from (arr[0], arr[1], ... arr[i])
        LMin[0] = arr[0];
        for (i = 1; i < n; ++i)
            LMin[i] = min(arr[i], LMin[i - 1]);
 
        // Construct RMax[] such that
        // RMax[j] stores the maximum value
        // from (arr[j], arr[j+1], ..arr[n-1])
        RMax[n - 1] = arr[n - 1];
        for (j = n - 2; j >= 0; --j)
            RMax[j] = max(arr[j], RMax[j + 1]);
 
        // Traverse both arrays from left
        // to right to find optimum j - i
        // This process is similar to merge()
        // of MergeSort
        i = 0;
        j = 0;
        maxDiff = -1;
        while (j < n && i < n) {
            if (LMin[i] < RMax[j]) {
                maxDiff = max(maxDiff, j - i);
                j = j + 1;
            }
            else
                i = i + 1;
        }
 
        return maxDiff;
    }
 
    // Driver program
    public static void Main()
    {
 
        int[] arr = { 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 };
        int n = arr.Length;
        int maxDiff = maxIndexDiff(arr, n);
        Console.Write(maxDiff);
    }
}
// This Code is Contributed by Sam007

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to find the maximum
// j – i such that arr[j] > arr[i]
 
// For a given array arr[],
// returns the maximum j - i
// such that arr[j] > arr[i]
function maxIndexDiff($arr, $n)
{
    $maxDiff = 0;
    $LMin = array_fill(0, $n, NULL);
    $RMax = array_fill(0, $n, NULL);
 
    // Construct LMin[] such that
    // LMin[i] stores the minimum
    // value from (arr[0], arr[1],
    // ... arr[i])
    $LMin[0] = $arr[0];
    for($i = 1; $i < $n; $i++)
        $LMin[$i] = min($arr[$i],
                        $LMin[$i - 1]);
 
    // Construct RMax[] such that
    // RMax[j] stores the maximum
    // value from (arr[j], arr[j+1],
    // ..arr[n-1])
    $RMax[$n - 1] = $arr[$n - 1];
    for($j = $n - 2; $j >= 0; $j--)
        $RMax[$j] = max($arr[$j],
                        $RMax[$j + 1]);
 
    // Traverse both arrays from left
    // to right to find optimum j - i
    // This process is similar to
    // merge() of MergeSort
    $i = 0;
    $j = 0;
    $maxDiff = -1;
    while ($j < $n && $i < $n)
        if ($LMin[$i] < $RMax[$j])
        {
            $maxDiff = max($maxDiff, $j - $i);
            $j = $j + 1;
        }
        else
            $i = $i + 1;
 
    return $maxDiff;
}
 
// Driver Code
$arr = array(9, 2, 3, 4, 5,
             6, 7, 8, 18, 0);
$n = sizeof($arr);
$maxDiff = maxIndexDiff($arr, $n);
echo $maxDiff;
 
// This code is contributed
// by ChitraNayal
?>

chevron_right


Output: 

8










 

Time Complexity: O(n) 
Auxiliary Space: O(n)
 

Asked in: Amazon,  Google,  VMWare

Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem.

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.




My Personal Notes arrow_drop_up

Recommended Posts:


Article Tags :
Practice Tags :


142


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.