Given an array arr[] of N positive integers. The task is to find the maximum of j – i subjected to the constraint of arr[i] <= arr[j].
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: 0
Method 1 (Simple but Inefficient): Run two loops. In the outer loop, pick elements one by one from the 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++
#include <bits/stdc++.h>
using namespace std;
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[] = { 1,1,1,1,1 };
int n = sizeof (arr) / sizeof (arr[0]);
int maxDiff = maxIndexDiff(arr, n);
cout << "\n" << maxDiff;
return 0;
}
|
C
#include <stdio.h>
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;
}
|
Java
public class FindMaximum {
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;
}
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);
}
}
|
Python3
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
arr = [ 9 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 18 , 0 ]
n = len (arr)
maxDiff = maxIndexDiff(arr, n)
print (maxDiff)
|
C#
using System;
class GFG {
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;
}
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);
}
}
|
PHP
<?php
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 ;
}
$arr = array (9, 2, 3, 4, 5,
6, 7, 8, 18, 0);
$n = count ( $arr );
$maxDiff = maxIndexDiff( $arr , $n );
echo $maxDiff ;
?>
|
Javascript
<script>
function maxIndexDiff(arr, n)
{
let maxDiff = -1;
let 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;
}
let arr = [ 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 ];
let n = arr.length;
let maxDiff = maxIndexDiff(arr, n);
document.write(maxDiff);
</script>
|
Time Complexity: O(n2)
Auxiliary Space: O(1)
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 that 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 with in an interview.
Approach :
- Traverse the array from the end and keep a track of the maximum number to the right of the current index including self
- Now we have a monotonous decreasing array, and we know we can use binary search to find the index of the rightmost greater element
- 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++
#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);
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]) {
ans = max(ans, mid);
low = mid + 1;
}
else {
high = mid - 1;
}
}
result = max(result, ans - i);
}
cout << result << endl;
}
|
C
#include <limits.h>
#include <stdio.h>
int max( int num1, int num2)
{
return (num1 > num2 ) ? num1 : num2;
}
int main()
{
int v[] = { 34, 8, 10, 3, 2, 80, 30, 33, 1 };
int n = sizeof (v) / sizeof (v[0]);
int maxFromEnd[n+1];
for ( int i = 0; i < n+1; i++) {
maxFromEnd[i] = INT_MIN;
}
for ( int i = n - 1; i >= 0; i--) {
maxFromEnd[i] = max(maxFromEnd[i + 1], v[i]);
}
int result = 0;
for ( int i = 0; i < n; i++) {
int low = i + 1, high = n - 1, ans = i;
while (low <= high) {
int mid = (low + high) / 2;
if (v[i] <= maxFromEnd[mid]) {
ans = max(ans, mid);
low = mid + 1;
}
else {
high = mid - 1;
}
}
result = max(result, ans - i);
}
printf ( "\n %d" , result);
}
|
Java
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);
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])
{
ans = Math.max(ans, mid);
low = mid + 1 ;
}
else
{
high = mid - 1 ;
}
}
result = Math.max(result, ans - i);
}
System.out.print(result + "\n" );
}
}
|
Python3
if __name__ = = '__main__' :
v = [ 34 , 8 , 10 , 3 ,
2 , 80 , 30 , 33 , 1 ];
n = len (v);
maxFromEnd = [ - 38749432 ] * (n + 1 );
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]):
ans = max (ans, mid);
low = mid + 1 ;
else :
high = mid - 1 ;
result = max (result, ans - i);
print (result, end = "");
|
C#
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;
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])
{
ans = Math.Max(ans, mid);
low = mid + 1;
}
else
{
high = mid - 1;
}
}
result = Math.Max(result, ans - i);
}
Console.Write(result + "\n" );
}
}
|
Javascript
<script>
let v = [34, 8, 10, 3, 2, 80, 30, 33, 1];
let n = v.length;
let maxFromEnd = new Array(n + 1);
for (let i = 0; i < maxFromEnd.length; i++)
maxFromEnd[i] = Number.MIN_VALUE;
for (let i = v.length - 1; i >= 0; i--)
{
maxFromEnd[i] = Math.max(maxFromEnd[i + 1], v[i]);
}
let result = 0;
for (let i = 0; i < v.length; i++)
{
let low = i + 1, high = v.length - 1, ans = i;
while (low <= high)
{
let mid = parseInt((low + high) / 2, 10);
if (v[i] <= maxFromEnd[mid])
{
ans = Math.max(ans, mid);
low = mid + 1;
}
else
{
high = mid - 1;
}
}
result = Math.max(result, ans - i);
}
document.write(result);
</script>
|
Time complexity : O(N*log(N))
Space complexity: O(N)
Method 3 O(n * log n): Use hashing and sorting to solve this problem in less than quadratic complexity after taking special care of the duplicates.
Approach :
- Traverse the array and store the index of each element in a list (to handle duplicates).
- Sort the array.
- Now traverse the array and keep track of the maximum difference of i and j.
- For j consider the last index from the list of possible indexes of the element and for i consider the first index from the list. (As the index was appended in ascending order).
- Keep updating the max difference till the end of the array.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxIndexDiff(vector< int >& arr, int n)
{
unordered_map< int , vector< int > > hashmap;
for ( int i = 0; i < n; i++) {
hashmap[arr[i]].push_back(i);
}
sort(arr.begin(), arr.end());
int maxDiff = INT_MIN;
int temp = n;
for ( int i = 0; i < n; i++) {
if (temp > hashmap[arr[i]][0]) {
temp = hashmap[arr[i]][0];
}
maxDiff = max(
maxDiff,
hashmap[arr[i]][hashmap[arr[i]].size() - 1]
- temp);
}
return maxDiff;
}
int main()
{
int n = 9;
vector< int > arr{ 34, 8, 10, 3, 2, 80, 30, 33, 1 };
int ans = maxIndexDiff(arr, n);
cout << "The maxIndexDiff is : " << ans << endl;
return 1;
}
|
Java
import java.io.*;
import java.util.*;
class GFG{
static int maxIndexDiff(ArrayList<Integer> arr, int n)
{
Map<Integer,
ArrayList<Integer>> hashmap = new HashMap<Integer,
ArrayList<Integer>>();
for ( int i = 0 ; i < n; i++)
{
if (hashmap.containsKey(arr.get(i)))
{
hashmap.get(arr.get(i)).add(i);
}
else
{
hashmap.put(arr.get(i), new ArrayList<Integer>());
hashmap.get(arr.get(i)).add(i);
}
}
Collections.sort(arr);
int maxDiff = Integer.MIN_VALUE;
int temp = n;
for ( int i = 0 ; i < n; i++)
{
if (temp > hashmap.get(arr.get(i)).get( 0 ))
{
temp = hashmap.get(arr.get(i)).get( 0 );
}
maxDiff = Math.max(maxDiff,
hashmap.get(arr.get(i)).get(
hashmap.get(arr.get(i)).size() - 1 ) - temp);
}
return maxDiff;
}
public static void main(String[] args)
{
int n = 9 ;
ArrayList<Integer> arr = new ArrayList<Integer>(
Arrays.asList( 34 , 8 , 10 , 3 , 2 , 80 , 30 , 33 , 1 ));
int ans = maxIndexDiff(arr, n);
System.out.println( "The maxIndexDiff is : " + ans);
}
}
|
Python3
n = 9
a = [ 34 , 8 , 10 , 3 , 2 , 80 , 30 , 33 , 1 ]
index = dict ()
for i in range (n):
if a[i] in index:
index[a[i]].append(i)
else :
index[a[i]] = [i]
a.sort()
maxDiff = 0
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)
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
static int maxIndexDiff(List< int > arr, int n)
{
Dictionary< int ,List< int >> hashmap = new Dictionary< int ,List< int >>();
for ( int i = 0; i < n; i++)
{
if (hashmap.ContainsKey(arr[i]))
{
hashmap[arr[i]].Add(i);
}
else
{
hashmap.Add(arr[i], new List< int >());
hashmap[arr[i]].Add(i);
}
}
arr.Sort();
int maxDiff = -1;
int temp = n;
for ( int i = 0; i < n; i++)
{
if (temp > hashmap[arr[i]][0] )
{
temp = hashmap[arr[i]][0];
}
maxDiff = Math.Max(maxDiff,hashmap[arr[i]][hashmap[arr[i]].Count - 1]- temp);
}
return maxDiff;
}
static public void Main (){
int n = 9;
List< int > arr = new List< int >();
arr.Add(34);
arr.Add(8);
arr.Add(10);
arr.Add(3);
arr.Add(2);
arr.Add(80);
arr.Add(30);
arr.Add(33);
arr.Add(1);
int ans = maxIndexDiff(arr, n);
Console.WriteLine( "The maxIndexDiff is : " + ans );
}
}
|
Javascript
<script>
function maxIndexDiff(arr,n)
{
let hashmap = new Map()
for (let i = 0; i < n; i++) {
hashmap[arr[i]] = hashmap[arr[i]] || []
hashmap[arr[i]].push(i)
}
arr.sort((a,b)=> (a - b))
let maxDiff = 0
let temp = n
for (let i = 0; i < n; i++) {
if (temp > hashmap[arr[i]][0]) {
temp = hashmap[arr[i]][0]
}
maxDiff = Math.max( maxDiff,hashmap[arr[i]][hashmap[arr[i]].length - 1]- temp )
}
return maxDiff
}
let n = 9
const arr = [ 34, 8, 10, 3, 2, 80, 30, 33, 1 ]
let ans = maxIndexDiff(arr, n)
document.write(`The maxIndexDiff is : ${ans}`)
</script>
|
Output
The maxIndexDiff is : 6
Time complexity : O(N*log(N))
Auxiliary Space: O(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 the 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 RMax[] 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.
Working Example:
Lets consider any example [7 3 1 8 9 10 4 5 6]
what is maxRight ?
Filling from right side 6 is first element now 6 > 5 so again we fill 6 till we reach 10 > 6 :
[10 10 10 10 10 10 6 6 6] this is maxR
[7 3 1 1 1 1 1 1 1 ] this is minL
now we see that how to reach answer from these to and its proof !!!
lets compare first elements of the arrays now we see 10 > 7,
now we increase maxR by 1 till it becomes lesser than 7 i.e at index 5
hence answer till now is. 5-0 = 5
now we will increase minL we get 3 which is lesser than 6 so we increase maxR till it reaches last index and the answer becomes 8-1= 7
so we see how we are getting correct answer.
As we need the max difference j – i such that A[i]<= A[j], hence we do not need to consider element after the index j and element before index i.
in previous hint, make 2 arrays,
First, will store smallest occurring element before the element
Second, will store largest occurring element after the element
Traverse the Second array, till the element in second array is larger than or equal to First array, and store the index difference. And if it becomes smaller, traverse the first array till it again becomes larger.
And store the max difference of this index difference.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
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)];
LMin[0] = arr[0];
for (i = 1; i < n; ++i)
LMin[i] = min(arr[i], LMin[i - 1]);
RMax[n - 1] = arr[n - 1];
for (j = n - 2; j >= 0; --j)
RMax[j] = max(arr[j], RMax[j + 1]);
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;
}
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;
}
|
C
#include <stdio.h>
int max( int x, int y)
{
return x > y ? x : y;
}
int min( int x, int y)
{
return x < y ? x : y;
}
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);
LMin[0] = arr[0];
for (i = 1; i < n; ++i)
LMin[i] = min(arr[i], LMin[i - 1]);
RMax[n - 1] = arr[n - 1];
for (j = n - 2; j >= 0; --j)
RMax[j] = max(arr[j], RMax[j + 1]);
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;
}
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;
}
|
Java
public class FindMaximum {
int max( int x, int y)
{
return x > y ? x : y;
}
int min( int x, int y)
{
return x < y ? x : y;
}
int maxIndexDiff( int arr[], int n)
{
int maxDiff;
int i, j;
int RMax[] = new int [n];
int LMin[] = new int [n];
LMin[ 0 ] = arr[ 0 ];
for (i = 1 ; i < n; ++i)
LMin[i] = min(arr[i], LMin[i - 1 ]);
RMax[n - 1 ] = arr[n - 1 ];
for (j = n - 2 ; j >= 0 ; --j)
RMax[j] = max(arr[j], RMax[j + 1 ]);
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;
}
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);
}
}
|
Python3
def max (a, b):
if (a > b):
return a
else :
return b
def min (a, b):
if (a < b):
return a
else :
return b
def maxIndexDiff(arr, n):
maxDiff = 0 ;
LMin = [ 0 ] * n
RMax = [ 0 ] * n
LMin[ 0 ] = arr[ 0 ]
for i in range ( 1 , n):
LMin[i] = min (arr[i], LMin[i - 1 ])
RMax[n - 1 ] = arr[n - 1 ]
for j in range (n - 2 , - 1 , - 1 ):
RMax[j] = max (arr[j], RMax[j + 1 ]);
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
if (__name__ = = '__main__' ):
arr = [ 9 , 2 , 3 , 4 , 5 ,
6 , 7 , 8 , 18 , 0 ]
n = len (arr)
maxDiff = maxIndexDiff(arr, n)
print (maxDiff)
|
C#
using System;
class GFG {
static int max( int x, int y)
{
return x > y ? x : y;
}
static int min( int x, int y)
{
return x < y ? x : y;
}
static int maxIndexDiff( int [] arr, int n)
{
int maxDiff;
int i, j;
int [] RMax = new int [n];
int [] LMin = new int [n];
LMin[0] = arr[0];
for (i = 1; i < n; ++i)
LMin[i] = min(arr[i], LMin[i - 1]);
RMax[n - 1] = arr[n - 1];
for (j = n - 2; j >= 0; --j)
RMax[j] = max(arr[j], RMax[j + 1]);
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;
}
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);
}
}
|
PHP
<?php
function maxIndexDiff( $arr , $n )
{
$maxDiff = 0;
$LMin = array_fill (0, $n , NULL);
$RMax = array_fill (0, $n , NULL);
$LMin [0] = $arr [0];
for ( $i = 1; $i < $n ; $i ++)
$LMin [ $i ] = min( $arr [ $i ],
$LMin [ $i - 1]);
$RMax [ $n - 1] = $arr [ $n - 1];
for ( $j = $n - 2; $j >= 0; $j --)
$RMax [ $j ] = max( $arr [ $j ],
$RMax [ $j + 1]);
$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 ;
}
$arr = array (9, 2, 3, 4, 5,
6, 7, 8, 18, 0);
$n = sizeof( $arr );
$maxDiff = maxIndexDiff( $arr , $n );
echo $maxDiff ;
?>
|
Javascript
<script>
function max(x, y)
{
return x > y ? x : y;
}
function min(x, y)
{
return x < y ? x : y;
}
function maxIndexDiff(arr, n)
{
let maxDiff;
let i, j;
let RMax = new Array(n);
let LMin = new Array(n);
LMin[0] = arr[0];
for (i = 1; i < n; ++i)
LMin[i] = min(arr[i], LMin[i - 1]);
RMax[n - 1] = arr[n - 1];
for (j = n - 2; j >= 0; --j)
RMax[j] = max(arr[j], RMax[j + 1]);
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;
}
let arr = [ 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 ];
let n = arr.length;
let maxDiff = maxIndexDiff(arr, n);
document.write(maxDiff);
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem.
Another Approach: ( only using one extra array ): We consider an auxiliary array : rightMax[] , such that, rightMax[i] = max element of the subarray arr[i…(n-1)], the largest or equal element after arr[i] element Suppose (arr[i], arr[jLast] ) is a pair, such that arr[jLast] is the last greater or equal element than arr[i]. For the pairs ending with arr[jLast] : ( arr[k], arr[jLast] ) for all k = (i+1) to jLast we don’t need to consider (jLast – k) because (jLast – i ) > (jLast – k) for all such k’s. So we can skip those pairs. Traversing from left to right of both arrays : arr[] and rightMax[] , when we first encounter rightMax[j] < arr[i[ , we know that jLast = j-1, and we can skip the pairs (arr[k], arr[jLast]) for all k = (i+1) to jLast. And also rightMax[] is non increasing sequence , so all elements at right side of rightMax[j] is smaller than or equal to rightMax[j]. But there may be arr[x] after arr[i] (x > i) such that arr[x] < rightMax[j] for x > i, so increment i when rightMax[j] < arr[i] is encountered.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxIndexDiff( int arr[], int n)
{
int rightMax[n];
rightMax[n-1]= arr[n-1];
for ( int i = n-2; i>=0; i--)
rightMax[i] = max(rightMax[i+1] , arr[i]);
int maxDist = INT_MIN;
int i = 0, j = 0;
while (i<n && j<n)
{
if (rightMax[j] >= arr[i])
{
maxDist = max( maxDist, j-i );
j++;
}
else
i++;
}
return maxDist;
}
int main()
{
int arr[] = { 34,8,10,3,2,80,30,33,1};
int n = sizeof (arr) / sizeof (arr[0]);
int maxDiff = maxIndexDiff(arr, n);
cout << maxDiff;
return 0;
}
|
Java
import java.util.*;
class GFG{
static int maxIndexDiff( int arr[], int n)
{
int []rightMax = new int [n];
rightMax[n- 1 ]= arr[n- 1 ];
for ( int i = n- 2 ; i>= 0 ; i--)
rightMax[i] = Math.max(rightMax[i+ 1 ] , arr[i]);
int maxDist = Integer.MIN_VALUE;
int i = 0 , j = 0 ;
while (i < n && j < n)
{
if (rightMax[j] >= arr[i])
{
maxDist = Math.max( maxDist, j-i );
j++;
}
else
i++;
}
return maxDist;
}
public static void main(String[] args)
{
int arr[] = { 34 , 8 , 10 , 3 , 2 , 80 , 30 , 33 , 1 };
int n = arr.length;
int maxDiff = maxIndexDiff(arr, n);
System.out.print(maxDiff);
}
}
|
Python3
def maxIndexDiff(arr, n):
rightMax = [ 0 ] * n
rightMax[n - 1 ] = arr[n - 1 ]
for i in range (n - 2 , - 1 , - 1 ):
rightMax[i] = max (rightMax[i + 1 ], arr[i])
maxDist = - 2 * * 31
i = 0
j = 0
while (i < n and j < n):
if (rightMax[j] > = arr[i]):
maxDist = max (maxDist, j - i)
j + = 1
else :
i + = 1
return maxDist
arr = [ 34 , 8 , 10 , 3 , 2 , 80 , 30 , 33 , 1 ]
n = len (arr)
maxDiff = maxIndexDiff(arr, n)
print (maxDiff)
|
C#
using System;
public class GFG
{
static int maxIndexDiff( int [] arr, int n)
{
int []rightMax = new int [n];
rightMax[n - 1] = arr[n - 1];
int i = 0, j = 0;
for (i = n - 2; i >= 0; i--)
rightMax[i] = Math.Max(rightMax[i+1] , arr[i]);
int maxDist = Int32.MinValue;
i = 0;
while (i < n && j < n)
{
if (rightMax[j] >= arr[i])
{
maxDist = Math.Max( maxDist, j - i);
j++;
}
else
i++;
}
return maxDist;
}
public static void Main()
{
int [] arr = {34, 8, 10, 3, 2, 80, 30, 33, 1};
int n = arr.Length;
int maxDiff = maxIndexDiff(arr, n);
Console.Write(maxDiff);
}
}
|
Javascript
<script>
function maxIndexDiff(arr, n)
{
var rightMax = new Array(n).fill(0);;
rightMax[n - 1] = arr[n - 1];
for ( var i = n - 2; i >= 0; i--){
rightMax[i] = Math.max(rightMax[i+1] , arr[i]);
}
var maxDist = Number.MIN_VALUE;
var i = 0;
var j = 0;
while (i < n && j < n)
{
if (rightMax[j] >= arr[i])
{
maxDist = Math.max( maxDist, j-i );
j++;
}
else
{ i++;
}
}
return maxDist;
}
var arr = [ 34,8,10,3,2,80,30,33,1];
var n = arr.length;
var maxDiff = maxIndexDiff(arr, n);
document.write(maxDiff);
</script>
|
Time complexity: O(n), As i and j pointers are traversing at most n elements, time complexity = O(n) + O(n) = O(n)
Auxiliary Space: O(n)
Using leftMin[]: We can also do this using leftMin[] array only , where leftMin[i] = min element of the subarray arr[0…i]
C++
#include <bits/stdc++.h>
using namespace std;
int maxIndexDiff( int arr[], int n)
{
int leftMin[n] ;
leftMin[0] = arr[0];
for ( int i = 1 ; i<n; i++)
leftMin[i] = min(leftMin[i-1], arr[i]);
int maxDist = INT_MIN;
int i = n-1, j = n-1;
while (i>=0 && j>=0)
{
if (arr[j] >= leftMin[i])
{
maxDist = max(maxDist, j-i);
i--;
}
else
j--;
}
return maxDist;
}
int main()
{
int arr[] = { 34,8,10,3,2,80,30,33,1};
int n = sizeof (arr) / sizeof (arr[0]);
int maxDiff = maxIndexDiff(arr, n);
cout << maxDiff;
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int maxIndexDiff( int arr[], int n)
{
int []leftMin = new int [n];
leftMin[ 0 ] = arr[ 0 ];
for ( int i = 1 ; i < n; i++)
leftMin[i] = Math.min(leftMin[i - 1 ] , arr[i]);
int maxDist = Integer.MIN_VALUE;
int i = n - 1 , j = n - 1 ;
while (i >= 0 && j >= 0 )
{
if (arr[j] >= leftMin[i])
{
maxDist = Math.max( maxDist, j - i );
i--;
}
else
j--;
}
return maxDist;
}
public static void main(String[] args)
{
int arr[] = { 34 , 8 , 10 , 3 , 2 , 80 , 30 , 33 , 1 };
int n = arr.length;
int maxDiff = maxIndexDiff(arr, n);
System.out.print(maxDiff);
}
}
|
Python3
def maxIndexDiff(arr, n):
leftMin = [ 0 ] * n
leftMin[ 0 ] = arr[ 0 ]
for i in range ( 1 ,n):
leftMin[i] = min (leftMin[i - 1 ], arr[i])
maxDist = - 2 * * 32
i = n - 1
j = n - 1
while (i> = 0 and j> = 0 ):
if (arr[j] > = leftMin[i]):
maxDist = max (maxDist, j - i)
i - = 1
else :
j - = 1
return maxDist
arr = [ 34 , 8 , 10 , 3 , 2 , 80 , 30 , 33 , 1 ]
n = len (arr)
maxDiff = maxIndexDiff(arr, n)
print (maxDiff)
|
C#
using System;
public class GFG{
static int maxIndexDiff( int [] arr, int n)
{
int []leftMin = new int [n];
leftMin[0] = arr[0];
int i,j;
for ( i = 1; i < n; i++)
leftMin[i] = Math.Min(leftMin[i - 1] , arr[i]);
int maxDist = Int32.MinValue;
i = n - 1;
j = n - 1;
while (i >= 0 && j >= 0)
{
if (arr[j] >= leftMin[i])
{
maxDist = Math.Max( maxDist, j - i );
i--;
}
else
j--;
}
return maxDist;
}
static public void Main ()
{
int [] arr = {34, 8, 10, 3, 2, 80, 30, 33, 1};
int n = arr.Length;
int maxDiff = maxIndexDiff(arr, n);
Console.Write(maxDiff);
}
}
|
Javascript
<script>
function maxIndexDiff(arr, n)
{
var leftMin = new Array(n).fill(0);;
leftMin[0] = arr[0];
for ( var i = 1; i < n; i++){
leftMin[i] = Math.min(leftMin[i-1] , arr[i]);
}
var maxDist = Number.MIN_VALUE;
var i = n-1;
var j = n-1;
while (i >= 0 && j >= 0)
{
if (arr[j] >= leftMin[i])
{
maxDist = Math.max( maxDist, j-i );
i--;
}
else
{ j--;
}
}
return maxDist;
}
var arr = [ 34,8,10,3,2,80,30,33,1];
var n = arr.length;
var maxDiff = maxIndexDiff(arr, n);
document.write(maxDiff);
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Please suggest if someone has a better solution that is more efficient in terms of space and time.
Another approach : Using Stack
Idea is :
1) First we do one traversal from left to right of array and store only those indexes in stack whose array values appears in decreasing order in stack.. This is because, say if any value at i and j is satisfying our condition A[ i ]<=A[ j ] and if any index k that appears before ith index i.e. k<i and if A[ k ]<= A[ i ] then value at kth index will also satisfy the condition A[k]<=A[ j ] . so we can ignore ith value .
2) Now we simpaly traverse from right of array with index i and comapre it with the top of stack .
if we find A[stack.peek()] <=A [i] we pop from stack and compare with next value else we decrement our i counter
at any point in loop if A[stack.peek()] <=A [i]. We compute tempMax = i – stack.peeak(). And keep updating maxSofar result.
below is the code for this Approach:
C++
#include<bits/stdc++.h>
using namespace std;
int maxIndexDiff( int A[], int N) {
stack< int > stkForIndex;
for ( int i=0;i<N;i++){
if (stkForIndex.empty() || A[stkForIndex.top()]>A[i])
stkForIndex.push(i);
}
int maxDiffSoFar = 0;
int tempdiff;
int i = N-1;
while (i>=0){
if (!stkForIndex.empty() && A[stkForIndex.top()] <= A[i]){
tempdiff = i - stkForIndex.top();
stkForIndex.pop();
if (tempdiff>maxDiffSoFar){
maxDiffSoFar = tempdiff;
}
continue ;
}
i--;
}
return maxDiffSoFar;
}
int main() {
int A[] = {34,8,10,3,2,80,30,33,1};
int N = sizeof (A) / sizeof ( int );
cout<< "Max diff be : " << maxIndexDiff(A, N);
}
|
Java
import java.io.*;
import java.util.Stack;
class GFG {
public static void main(String[] args) {
int A[] = { 34 , 8 , 10 , 3 , 2 , 80 , 30 , 33 , 1 };
int N = A.length;
System.out.println( "Max diff be : " + maxIndexDiff(A, N));
}
static int maxIndexDiff( int A[], int N) {
Stack<Integer> stkForIndex = new Stack<>();
for ( int i= 0 ;i<N;i++){
if (stkForIndex.isEmpty() || A[stkForIndex.peek()]>A[i])
stkForIndex.push(i);
}
int maxDiffSoFar = 0 ;
int tempdiff;
int i = N- 1 ;
while (i>= 0 ){
if (!stkForIndex.isEmpty() && A[stkForIndex.peek()] <= A[i]){
tempdiff = i - stkForIndex.pop();
if (tempdiff>maxDiffSoFar){
maxDiffSoFar = tempdiff;
}
continue ;
}
i--;
}
return maxDiffSoFar;
}
}
|
Python3
def maxIndexDiff( A, N) :
stkForIndex = list ();
for i in range ( 0 , N):
if ( len (stkForIndex) = = 0 or A[stkForIndex[ - 1 ]] > A[i]):
stkForIndex.append(i);
maxDiffSoFar = 0 ;
tempdiff = - 1 ;
i = N - 1 ;
while (i > = 0 ):
if ( len (stkForIndex) and A[stkForIndex[ - 1 ]] < = A[i]):
tempdiff = i - stkForIndex.pop();
if (tempdiff > maxDiffSoFar):
maxDiffSoFar = tempdiff;
continue ;
i - = 1 ;
return maxDiffSoFar;
A = [ 34 , 8 , 10 , 3 , 2 , 80 , 30 , 33 , 1 ];
N = len (A);
print ( "Max diff be :" , maxIndexDiff(A, N));
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
public class Gfg
{
static int maxIndexDiff( int [] A, int N)
{
Stack< int > stkForIndex = new Stack< int >();
int i = 0;
for (i = 0; i < N; i++){
if (stkForIndex.Count == 0 || A[stkForIndex.Peek()] > A[i])
stkForIndex.Push(i);
}
int maxDiffSoFar = 0;
int tempdiff;
i = N-1;
while (i >= 0){
if (stkForIndex.Count!=0 && A[stkForIndex.Peek()] <= A[i]){
tempdiff = i - stkForIndex.Peek();
stkForIndex.Pop();
if (tempdiff > maxDiffSoFar){
maxDiffSoFar = tempdiff;
}
continue ;
}
i--;
}
return maxDiffSoFar;
}
public static void Main( string [] args)
{
int [] A = {34,8,10,3,2,80,30,33,1};
int N = A.Length;
Console.Write( "Max diff be : " + maxIndexDiff(A, N));
}
}
|
Javascript
function maxIndexDiff(A, N)
{
let stkForIndex = [];
for (let i = 0; i < N; i++)
{
if (stkForIndex.length === 0 || A[stkForIndex[stkForIndex.length - 1]] > A[i]) {
stkForIndex.push(i);
}
}
let maxDiffSoFar = 0;
let tempdiff;
let i = N - 1;
while (i >= 0) {
if (stkForIndex.length !== 0 && A[stkForIndex[stkForIndex.length - 1]] <= A[i]) {
tempdiff = i - stkForIndex[stkForIndex.length - 1];
stkForIndex.pop();
if (tempdiff > maxDiffSoFar) {
maxDiffSoFar = tempdiff;
}
continue ;
}
i--;
}
return maxDiffSoFar;
}
let A = [34, 8, 10, 3, 2, 80, 30, 33, 1];
let N = A.length;
console.log( "Max diff be : " + maxIndexDiff(A, N));
|
Time complexity: O(n), As it requires two traversal so TC is O(n) + O(n) = O(n)
Auxiliary Space: O(n) O(n) is its worst case complexity in case whole array is already sorted in decreasing order.Other wise it stores only those values which appears in decreasing order.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...