Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Maximum j - i in an array such that arr[i] <= arr[j]
Next article icon

Maximum j - i in an array such that arr[i] <= arr[j]

Last Updated : 25 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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] and i <= j.

Examples : 

Input: arr[] = [34, 8, 10, 3, 2, 80, 30, 33, 1]
Output: 6
Explanation: for i = 1 and j = 7.

Input: arr[] = [1, 2, 3, 4, 5, 6]
Output: 5
Explanation: For i = 0 and j = 5, arr[j] >= arr[i] and j - i is maximum

Input: [6, 5, 4, 3, 2, 1]
Output: 0
Explanation: Take any i and j where i == j.

[Naive Approach] Using Two Nested Loops - O(n^2) time and O(1) space

The idea is to use a nested loop approach where for each element in the array, we compare it with every subsequent element to check if the condition arr[i] <= arr[j] is satisfied. If the condition is met, we calculate the difference between the indices j and i and keep track of the maximum difference found.

C++
// C++ program to find the maximum  // j – i such that arr[i] <= arr[j] #include <bits/stdc++.h> using namespace std;  int maxIndexDiff(vector<int> &arr) { 	int n = arr.size(); 	 	int ans = 0; 	 	for (int i=0; i<n; i++) { 	    for (int j=i+1; j<n; j++) { 	         	        // If arr[i] <= arr[j] 	        if (arr[i] <= arr[j]) { 	            ans = max(ans, j-i); 	        } 	    } 	} 	 	return ans; }  int main() { 	vector<int> arr = {34, 8, 10, 3, 2, 80, 30, 33, 1}; 	cout << maxIndexDiff(arr); 	return 0; } 
Java
// Java program to find the maximum  // j – i such that arr[i] <= arr[j] import java.util.*;  class GfG {          static int maxIndexDiff(int[] arr) {         int n = arr.length;                  int ans = 0;                  for (int i = 0; i < n; i++) {             for (int j = i + 1; j < n; j++) {                                  // If arr[i] <= arr[j]                 if (arr[i] <= arr[j]) {                     ans = Math.max(ans, j - i);                 }             }         }                  return ans;     }      public static void main(String[] args) {         int[] arr = {34, 8, 10, 3, 2, 80, 30, 33, 1};         System.out.println(maxIndexDiff(arr));     } } 
Python
# Python program to find the maximum  # j – i such that arr[i] <= arr[j]  def maxIndexDiff(arr):     n = len(arr)          ans = 0          for i in range(n):         for j in range(i + 1, n):                          # If arr[i] <= arr[j]             if arr[i] <= arr[j]:                 ans = max(ans, j - i)          return ans  if __name__ == "__main__":     arr = [34, 8, 10, 3, 2, 80, 30, 33, 1]     print(maxIndexDiff(arr)) 
C#
// C# program to find the maximum  // j – i such that arr[i] <= arr[j] using System;  class GfG {          static int maxIndexDiff(int[] arr) {         int n = arr.Length;                  int ans = 0;                  for (int i = 0; i < n; i++) {             for (int j = i + 1; j < n; j++) {                                  // If arr[i] <= arr[j]                 if (arr[i] <= arr[j]) {                     ans = Math.Max(ans, j - i);                 }             }         }                  return ans;     }      static void Main() {         int[] arr = {34, 8, 10, 3, 2, 80, 30, 33, 1};         Console.WriteLine(maxIndexDiff(arr));     } } 
JavaScript
// JavaScript program to find the maximum  // j – i such that arr[i] <= arr[j]  function maxIndexDiff(arr) {     let n = arr.length;          let ans = 0;          for (let i = 0; i < n; i++) {         for (let j = i + 1; j < n; j++) {                          // If arr[i] <= arr[j]             if (arr[i] <= arr[j]) {                 ans = Math.max(ans, j - i);             }         }     }          return ans; }  let arr = [34, 8, 10, 3, 2, 80, 30, 33, 1]; console.log(maxIndexDiff(arr)); 

Output
6

[Better Approach - 1] Using Decreasing Array and Binary Search - O(n Log n) time and O(n) space

 The idea is to maintain a list of indices in decreasing order of their corresponding array values and use binary search to efficiently find the smallest index i such that arr[i] <= arr[j] for each j, thereby maximizing j - i.

Step by step approach:

  1. Maintain a list of indices where values are in decreasing order.
  2. For each element, if it is smaller than the last element in the list, add its index to the list.
  3. Otherwise, use binary search to find the smallest index in the list where the value is less than or equal to the current element.
  4. Calculate the difference between the current index and the found index, and update the maximum difference if this difference is larger.
C++
// C++ program to find the maximum // j - i such that arr[i] <= arr[j] #include <bits/stdc++.h> using namespace std;  // Function to find the minimum index for  // which arr[index] <= val. int binary(vector<int> &dec, vector<int> &arr, int val) { 	int s = 0, e = dec.size()-1, ans = e; 	while (s<=e) { 		int mid = s + (e-s)/2; 		int v = arr[dec[mid]]; 		if (v <= val) { 			ans = mid; 			e = mid - 1; 		} else { 			s = mid + 1; 		} 	}  	return dec[ans]; }  // Function to find the maximum // j - i such that arr[i] <= arr[j] int maxIndexDiff(vector<int>& arr) { 	 	// Array to store indices of elements  	// in decreasing order of value. 	vector<int> dec; 	dec.push_back(0);  	int ans = 0; 	 	for (int j=1; j<arr.size(); j++) { 	     	    // If arr[j] is smallest value encountered 	    // so far, append it to dec array. 		if (arr[j] < arr[dec.back()]) { 		    dec.push_back(j); 		} 		 		// Else, search for the minimum value  		// of i,such that arr[i] <= arr[j] 		else { 			int i = binary(dec, arr, arr[j]); 			ans = max(ans, j - i); 		} 	}  	return ans; }  int main() { 	vector<int> arr = {34, 8, 10, 3, 2, 80, 30, 33, 1}; 	cout << maxIndexDiff(arr); 	return 0; } 
Java
// Java program to find the maximum // j - i such that arr[i] <= arr[j] import java.util.*;  class GfG {      // Function to find the minimum index for      // which arr[index] <= val.     static int binary(ArrayList<Integer> dec, int[] arr, int val) {         int s = 0, e = dec.size() - 1, ans = e;         while (s <= e) {             int mid = s + (e - s) / 2;             int v = arr[dec.get(mid)];             if (v <= val) {                 ans = mid;                 e = mid - 1;             } else {                 s = mid + 1;             }         }         return dec.get(ans);     }      // Function to find the maximum     // j - i such that arr[i] <= arr[j]     static int maxIndexDiff(int[] arr) {          // Array to store indices of elements          // in decreasing order of value.         ArrayList<Integer> dec = new ArrayList<>();         dec.add(0);          int ans = 0;          for (int j = 1; j < arr.length; j++) {              // If arr[j] is smallest value encountered             // so far, append it to dec array.             if (arr[j] < arr[dec.get(dec.size() - 1)]) {                 dec.add(j);             }              // Else, search for the minimum value              // of i, such that arr[i] <= arr[j]             else {                 int i = binary(dec, arr, arr[j]);                 ans = Math.max(ans, j - i);             }         }          return ans;     }      public static void main(String[] args) {         int[] arr = {34, 8, 10, 3, 2, 80, 30, 33, 1};         System.out.println(maxIndexDiff(arr));     } } 
Python
# Python program to find the maximum # j - i such that arr[i] <= arr[j]  # Function to find the minimum index for  # which arr[index] <= val. def binary(dec, arr, val):     s, e, ans = 0, len(dec) - 1, len(dec) - 1     while s <= e:         mid = s + (e - s) // 2         v = arr[dec[mid]]         if v <= val:             ans = mid             e = mid - 1         else:             s = mid + 1     return dec[ans]  # Function to find the maximum # j - i such that arr[i] <= arr[j] def maxIndexDiff(arr):          # Array to store indices of elements      # in decreasing order of value.     dec = [0]      ans = 0      for j in range(1, len(arr)):          # If arr[j] is smallest value encountered         # so far, append it to dec array.         if arr[j] < arr[dec[-1]]:             dec.append(j)          # Else, search for the minimum value          # of i, such that arr[i] <= arr[j]         else:             i = binary(dec, arr, arr[j])             ans = max(ans, j - i)      return ans  if __name__ == "__main__":     arr = [34, 8, 10, 3, 2, 80, 30, 33, 1]     print(maxIndexDiff(arr)) 
C#
// C# program to find the maximum // j - i such that arr[i] <= arr[j] using System; using System.Collections.Generic;  class GfG {      // Function to find the minimum index for      // which arr[index] <= val.     static int binary(List<int> dec, int[] arr, int val) {         int s = 0, e = dec.Count - 1, ans = e;         while (s <= e) {             int mid = s + (e - s) / 2;             int v = arr[dec[mid]];             if (v <= val) {                 ans = mid;                 e = mid - 1;             } else {                 s = mid + 1;             }         }         return dec[ans];     }      // Function to find the maximum     // j - i such that arr[i] <= arr[j]     static int maxIndexDiff(int[] arr) {          // Array to store indices of elements          // in decreasing order of value.         List<int> dec = new List<int>();         dec.Add(0);          int ans = 0;          for (int j = 1; j < arr.Length; j++) {              // If arr[j] is smallest value encountered             // so far, append it to dec array.             if (arr[j] < arr[dec[dec.Count - 1]]) {                 dec.Add(j);             }              // Else, search for the minimum value              // of i, such that arr[i] <= arr[j]             else {                 int i = binary(dec, arr, arr[j]);                 ans = Math.Max(ans, j - i);             }         }          return ans;     }      static void Main() {         int[] arr = {34, 8, 10, 3, 2, 80, 30, 33, 1};         Console.WriteLine(maxIndexDiff(arr));     } } 
JavaScript
// JavaScript program to find the maximum // j - i such that arr[i] <= arr[j]  function binary(dec, arr, val) {     let s = 0, e = dec.length - 1, ans = e;     while (s <= e) {         let mid = Math.floor(s + (e - s) / 2);         let v = arr[dec[mid]];         if (v <= val) {             ans = mid;             e = mid - 1;         } else {             s = mid + 1;         }     }     return dec[ans]; }  // Function to find the maximum // j - i such that arr[i] <= arr[j] function maxIndexDiff(arr) {      // Array to store indices of elements      // in decreasing order of value.     let dec = [];     dec.push(0);      let ans = 0;      for (let j = 1; j < arr.length; j++) {          // If arr[j] is smallest value encountered         // so far, append it to dec array.         if (arr[j] < arr[dec[dec.length - 1]]) {             dec.push(j);         }          // Else, search for the minimum value          // of i, such that arr[i] <= arr[j]         else {             let i = binary(dec, arr, arr[j]);             ans = Math.max(ans, j - i);         }     }      return ans; }  let arr = [34, 8, 10, 3, 2, 80, 30, 33, 1]; console.log(maxIndexDiff(arr)); 

Output
6

[Better Approach - 2] Using Sorting - O(n Log n) time and O(n) space

The idea is to maximize the difference between two elements (j - i) where arr[i] <= arr[j] by sorting the array along with their original indices, then finding the maximum valid difference in sorted order. Since sorting guarantees the value constraint (arr[i] <= arr[j]), we only need to find index pairs that maximize j - i while maintaining the original positional relationship.

Step by step approach:

  • Sort the array elements along with their original indices to ensure the value condition is always satisfied.
  • Track the minimum index seen so far while iterating through the sorted array.
  • For each position in the sorted array, calculate the difference between current index and minimum index. Update the answer with maximum difference found.
C++
// C++ program to find the maximum // j - i such that arr[i] <= arr[j] #include <bits/stdc++.h> using namespace std;  // Function to find the maximum // j - i such that arr[i] <= arr[j] int maxIndexDiff(vector<int>& arr) {      	vector<vector<int>> v; 	 	// Store the values and their  	// corresponding indices. 	for (int i=0; i<arr.size(); i++) { 		v.push_back({arr[i], i}); 	}          // Sort the array so that the condition     // arr[i] <= arr[j] is always true. 	sort(v.begin(), v.end());          // Variable to store the minimum index. 	int i = v[0][1]; 	int ans = 0; 	 	// For each value, the condition is  	// already true, so just compare  	// j - i with answer. 	for (int j=1; j<v.size(); j++) { 		ans = max(ans, v[j][1] - i); 		i = min(i, v[j][1]); 	}  	return ans; }  int main() { 	vector<int> arr = {34, 8, 10, 3, 2, 80, 30, 33, 1}; 	cout << maxIndexDiff(arr); 	return 0; } 
Java
// Java program to find the maximum // j - i such that arr[i] <= arr[j] import java.util.Arrays;  class GfG {      // Function to find the maximum     // j - i such that arr[i] <= arr[j]     static int maxIndexDiff(int[] arr) {                  int[][] v = new int[arr.length][2];                  // Store the values and their          // corresponding indices.         for (int i = 0; i < arr.length; i++) {             v[i][0] = arr[i];             v[i][1] = i;         }                  // Sort the array so that the condition         // arr[i] <= arr[j] is always true.         Arrays.sort(v, (a, b) -> Integer.compare(a[0], b[0]));                  // Variable to store the minimum index.         int i = v[0][1];         int ans = 0;                  // For each value, the condition is          // already true, so just compare          // j - i with answer.         for (int j = 1; j < v.length; j++) {             ans = Math.max(ans, v[j][1] - i);             i = Math.min(i, v[j][1]);         }          return ans;     }      public static void main(String[] args) {         int[] arr = {34, 8, 10, 3, 2, 80, 30, 33, 1};         System.out.println(maxIndexDiff(arr));     } } 
Python
# Python program to find the maximum # j - i such that arr[i] <= arr[j]  # Function to find the maximum # j - i such that arr[i] <= arr[j] def maxIndexDiff(arr):          v = []          # Store the values and their      # corresponding indices.     for i in range(len(arr)):         v.append([arr[i], i])          # Sort the array so that the condition     # arr[i] <= arr[j] is always true.     v.sort()          # Variable to store the minimum index.     i = v[0][1]     ans = 0          # For each value, the condition is      # already true, so just compare      # j - i with answer.     for j in range(1, len(v)):         ans = max(ans, v[j][1] - i)         i = min(i, v[j][1])      return ans  if __name__ == "__main__":     arr = [34, 8, 10, 3, 2, 80, 30, 33, 1]     print(maxIndexDiff(arr)) 
C#
// C# program to find the maximum // j - i such that arr[i] <= arr[j] using System;  class GfG {      // Function to find the maximum     // j - i such that arr[i] <= arr[j]     static int maxIndexDiff(int[] arr) {                  int[][] v = new int[arr.Length][];                  // Store the values and their          // corresponding indices.         for (int j = 0; j < arr.Length; j++) {             v[j] = new int[] { arr[j], j };         }                  // Sort the array so that the condition         // arr[i] <= arr[j] is always true.         Array.Sort(v, (a, b) => a[0].CompareTo(b[0]));                  // Variable to store the minimum index.         int i = v[0][1];         int ans = 0;                  // For each value, the condition is          // already true, so just compare          // j - i with answer.         for (int j = 1; j < v.Length; j++) {             ans = Math.Max(ans, v[j][1] - i);             i = Math.Min(i, v[j][1]);         }          return ans;     }      static void Main() {         int[] arr = {34, 8, 10, 3, 2, 80, 30, 33, 1};         Console.WriteLine(maxIndexDiff(arr));     } } 
JavaScript
// JavaScript program to find the maximum // j - i such that arr[i] <= arr[j]  // Function to find the maximum // j - i such that arr[i] <= arr[j] function maxIndexDiff(arr) {          let v = [];          // Store the values and their      // corresponding indices.     for (let i = 0; i < arr.length; i++) {         v.push([arr[i], i]);     }          // Sort the array so that the condition     // arr[i] <= arr[j] is always true.     v.sort((a, b) => a[0] - b[0]);          // Variable to store the minimum index.     let i = v[0][1];     let ans = 0;          // For each value, the condition is      // already true, so just compare      // j - i with answer.     for (let j = 1; j < v.length; j++) {         ans = Math.max(ans, v[j][1] - i);         i = Math.min(i, v[j][1]);     }      return ans; }  let arr = [34, 8, 10, 3, 2, 80, 30, 33, 1]; console.log(maxIndexDiff(arr)); 

Output
6

[Expected Approach - 1] Using Precomputed Min Max Values - O(n) time and O(n) space

The idea is to precompute minimum values from left to right and maximum values from right to left, then use a two-pointer approach to find the maximum valid distance. By having these preprocessed arrays, we can efficiently check if the condition arr[i] <= arr[j] is satisfied without examining every possible pair, allowing us to incrementally search for the largest possible j-i difference.

Step by step approach:

  1. Precompute the minimum values from left to right for each position.
  2. Precompute the maximum values from right to left for each position.
  3. Use two pointers starting at the beginning of both arrays.
  4. When the minimum value is less than or equal to maximum value, record the distance and move right pointer.
  5. When the condition fails, move the left pointer to find a smaller minimum value.

Illustration:

Let's consider the array [34, 8, 10, 3, 2, 80, 30, 33, 1]:

  1. First we build lMin array (minimum values from left to right):
    • [34, 8, 8, 3, 2, 2, 2, 2, 1]
  2. Then we build rMax array (maximum values from right to left):
    • [80, 80, 80, 80, 80, 80, 33, 33, 1]
  3. Starting with i=0, j=0: lMin[0]=34, rMax[0]=80,
    • condition is satisfied (34≤80), record diff=0, increment j
  4. At i=0, j=5: lMin[0]=34, rMax[5]=80, max diff=5,
    • increment j
  5. Continue until i=1, j=8: lMin[1]=8, rMax[8]=1,
    • condition fails (8>1), increment i
  6. At i=4, j=7: lMin[4]=2, rMax[7]=33,
    • condition satisfied (2≤33), max diff=3, increment j
  7. Final result: When we've exhausted all valid combinations, the maximum difference found is 7 (occurring when i=1, j=8 - the difference right before condition failed)
C++
// C++ program to find the maximum // j - i such that arr[i] <= arr[j] #include <bits/stdc++.h> using namespace std;  // Function to find the maximum // j - i such that arr[i] <= arr[j] int maxIndexDiff(vector<int>& arr) {      	int n = arr.size(); 	vector<int> lMin(n), rMax(n); 	int i, j; 	 	// lMin[i] stores the minimum value  	// in the range [0, i] 	lMin[0] = arr[0]; 	for (i=1; i<n; i++) { 	    lMin[i] = min(lMin[i-1], arr[i]); 	} 	 	// rMax[i] stores the maximum value 	// in the range [i, n-1] 	rMax[n-1] = arr[n-1]; 	for (i=n-2; i>=0; i--) { 	    rMax[i] = max(rMax[i+1], arr[i]); 	} 	 	i = 0; 	j = 0; 	int ans = 0; 	 	while (i<n && j<n) { 	     	    // Compare with answer and increment 	    // j. 	    if (lMin[i] <= rMax[j]) { 	        ans = max(ans, j-i); 	        j++; 	    } 	     	    // Else, increment i. 	    else { 	        i++; 	    } 	} 	 	return ans; }  int main() { 	vector<int> arr = {34, 8, 10, 3, 2, 80, 30, 33, 1}; 	cout << maxIndexDiff(arr); 	return 0; } 
Java
// Java program to find the maximum // j - i such that arr[i] <= arr[j] import java.util.*;  class GfG {          // Function to find the maximum     // j - i such that arr[i] <= arr[j]     static int maxIndexDiff(int[] arr) {                  int n = arr.length;         int[] lMin = new int[n], rMax = new int[n];         int i, j;                  // lMin[i] stores the minimum value          // in the range [0, i]         lMin[0] = arr[0];         for (i = 1; i < n; i++) {             lMin[i] = Math.min(lMin[i - 1], arr[i]);         }                  // rMax[i] stores the maximum value         // in the range [i, n-1]         rMax[n - 1] = arr[n - 1];         for (i = n - 2; i >= 0; i--) {             rMax[i] = Math.max(rMax[i + 1], arr[i]);         }                  i = 0;         j = 0;         int ans = 0;                  while (i < n && j < n) {                          // Compare with answer and increment             // j.             if (lMin[i] <= rMax[j]) {                 ans = Math.max(ans, j - i);                 j++;             }                          // Else, increment i.             else {                 i++;             }         }                  return ans;     }      public static void main(String[] args) {         int[] arr = {34, 8, 10, 3, 2, 80, 30, 33, 1};         System.out.println(maxIndexDiff(arr));     } } 
Python
# Python program to find the maximum # j - i such that arr[i] <= arr[j]  # Function to find the maximum # j - i such that arr[i] <= arr[j] def maxIndexDiff(arr):          n = len(arr)     lMin = [0] * n     rMax = [0] * n          # lMin[i] stores the minimum value      # in the range [0, i]     lMin[0] = arr[0]     for i in range(1, n):         lMin[i] = min(lMin[i - 1], arr[i])          # rMax[i] stores the maximum value     # in the range [i, n-1]     rMax[n - 1] = arr[n - 1]     for i in range(n - 2, -1, -1):         rMax[i] = max(rMax[i + 1], arr[i])          i = 0     j = 0     ans = 0          while i < n and j < n:                  # Compare with answer and increment         # j.         if lMin[i] <= rMax[j]:             ans = max(ans, j - i)             j += 1                  # Else, increment i.         else:             i += 1          return ans  if __name__ == "__main__":     arr = [34, 8, 10, 3, 2, 80, 30, 33, 1]     print(maxIndexDiff(arr)) 
C#
// C# program to find the maximum // j - i such that arr[i] <= arr[j] using System;  class GfG {          // Function to find the maximum     // j - i such that arr[i] <= arr[j]     static int maxIndexDiff(int[] arr) {                  int n = arr.Length;         int[] lMin = new int[n], rMax = new int[n];         int i, j;                  // lMin[i] stores the minimum value          // in the range [0, i]         lMin[0] = arr[0];         for (i = 1; i < n; i++) {             lMin[i] = Math.Min(lMin[i - 1], arr[i]);         }                  // rMax[i] stores the maximum value         // in the range [i, n-1]         rMax[n - 1] = arr[n - 1];         for (i = n - 2; i >= 0; i--) {             rMax[i] = Math.Max(rMax[i + 1], arr[i]);         }                  i = 0;         j = 0;         int ans = 0;                  while (i < n && j < n) {                          // Compare with answer and increment             // j.             if (lMin[i] <= rMax[j]) {                 ans = Math.Max(ans, j - i);                 j++;             }                          // Else, increment i.             else {                 i++;             }         }                  return ans;     }      static void Main() {         int[] arr = {34, 8, 10, 3, 2, 80, 30, 33, 1};         Console.WriteLine(maxIndexDiff(arr));     } } 
JavaScript
// JavaScript program to find the maximum // j - i such that arr[i] <= arr[j]  // Function to find the maximum // j - i such that arr[i] <= arr[j] function maxIndexDiff(arr) {          let n = arr.length;     let lMin = new Array(n), rMax = new Array(n);          // lMin[i] stores the minimum value      // in the range [0, i]     lMin[0] = arr[0];     for (let i = 1; i < n; i++) {         lMin[i] = Math.min(lMin[i - 1], arr[i]);     }          // rMax[i] stores the maximum value     // in the range [i, n-1]     rMax[n - 1] = arr[n - 1];     for (let i = n - 2; i >= 0; i--) {         rMax[i] = Math.max(rMax[i + 1], arr[i]);     }          let i = 0, j = 0, ans = 0;          while (i < n && j < n) {                  // Compare with answer and increment         // j.         if (lMin[i] <= rMax[j]) {             ans = Math.max(ans, j - i);             j++;         }                  // Else, increment i.         else {             i++;         }     }          return ans; }  let arr = [34, 8, 10, 3, 2, 80, 30, 33, 1]; console.log(maxIndexDiff(arr)); 

Output
6

[Expected Approach - 2] Using Precomputed Max (or Min) Array - O(n) time and O(n) space

The idea is to optimize the previous two-array approach by eliminating the need for the lMin array and instead dynamically updating a single lMin variable while maintaining the two-pointer technique of finding the maximum index difference.

C++
// C++ program to find the maximum // j - i such that arr[i] <= arr[j] #include <bits/stdc++.h> using namespace std;  // Function to find the maximum // j - i such that arr[i] <= arr[j] int maxIndexDiff(vector<int>& arr) {     int n = arr.size();     vector<int> rMax(n);     int i, j;     int lMin;          // rMax[i] stores the maximum value     // in the range [i, n-1]     rMax[n-1] = arr[n-1];     for (i=n-2; i>=0; i--) {         rMax[i] = max(rMax[i+1], arr[i]);     }          i = 0;     j = 0;     int ans = 0;     lMin = arr[0];          while (i<n && j<n) {                  // Compare with answer and increment j.         if (lMin <= rMax[j]) {             ans = max(ans, j-i);             j++;         }                  // Else, increment i.         else {             i++;             if (i+1 < n)                  lMin = min(lMin, arr[i]);         }     }          return ans; }  int main() {     vector<int> arr = {34, 8, 10, 3, 2, 80, 30, 33, 1};     cout << maxIndexDiff(arr);     return 0; } 
Java
// Java program to find the maximum // j - i such that arr[i] <= arr[j] import java.util.*;  class GfG {          // Function to find the maximum     // j - i such that arr[i] <= arr[j]     static int maxIndexDiff(int[] arr) {         int n = arr.length;         int[] rMax = new int[n];         int i, j;         int lMin;                  // rMax[i] stores the maximum value         // in the range [i, n-1]         rMax[n - 1] = arr[n - 1];         for (i = n - 2; i >= 0; i--) {             rMax[i] = Math.max(rMax[i + 1], arr[i]);         }                  i = 0;         j = 0;         int ans = 0;         lMin = arr[0];                  while (i < n && j < n) {                          // Compare with answer and increment j.             if (lMin <= rMax[j]) {                 ans = Math.max(ans, j - i);                 j++;             }                          // Else, increment i.             else {                 i++;                 if (i + 1 < n)                      lMin = Math.min(lMin, arr[i]);             }         }                  return ans;     }      public static void main(String[] args) {         int[] arr = {34, 8, 10, 3, 2, 80, 30, 33, 1};         System.out.println(maxIndexDiff(arr));     } } 
Python
# Python program to find the maximum # j - i such that arr[i] <= arr[j]  # Function to find the maximum # j - i such that arr[i] <= arr[j] def maxIndexDiff(arr):     n = len(arr)     rMax = [0] * n     i, j = 0, 0     lMin = arr[0]          # rMax[i] stores the maximum value     # in the range [i, n-1]     rMax[n - 1] = arr[n - 1]     for i in range(n - 2, -1, -1):         rMax[i] = max(rMax[i + 1], arr[i])          i, j, ans = 0, 0, 0          while i < n and j < n:                  # Compare with answer and increment j.         if lMin <= rMax[j]:             ans = max(ans, j - i)             j += 1                  # Else, increment i.         else:             i += 1             if i + 1 < n:                 lMin = min(lMin, arr[i])          return ans  if __name__ == "__main__":     arr = [34, 8, 10, 3, 2, 80, 30, 33, 1]     print(maxIndexDiff(arr)) 
C#
// C# program to find the maximum // j - i such that arr[i] <= arr[j] using System;  class GfG {          // Function to find the maximum     // j - i such that arr[i] <= arr[j]     static int maxIndexDiff(int[] arr) {         int n = arr.Length;         int[] rMax = new int[n];         int i, j;         int lMin;                  // rMax[i] stores the maximum value         // in the range [i, n-1]         rMax[n - 1] = arr[n - 1];         for (i = n - 2; i >= 0; i--) {             rMax[i] = Math.Max(rMax[i + 1], arr[i]);         }                  i = 0;         j = 0;         int ans = 0;         lMin = arr[0];                  while (i < n && j < n) {                          // Compare with answer and increment j.             if (lMin <= rMax[j]) {                 ans = Math.Max(ans, j - i);                 j++;             }                          // Else, increment i.             else {                 i++;                 if (i + 1 < n)                      lMin = Math.Min(lMin, arr[i]);             }         }                  return ans;     }      static void Main() {         int[] arr = {34, 8, 10, 3, 2, 80, 30, 33, 1};         Console.WriteLine(maxIndexDiff(arr));     } } 
JavaScript
// JavaScript program to find the maximum // j - i such that arr[i] <= arr[j]   // Function to find the maximum // j - i such that arr[i] <= arr[j] function maxIndexDiff(arr) {     let n = arr.length;     let rMax = new Array(n);     let i, j;     let lMin;          // rMax[i] stores the maximum value     // in the range [i, n-1]     rMax[n - 1] = arr[n - 1];     for (i = n - 2; i >= 0; i--) {         rMax[i] = Math.max(rMax[i + 1], arr[i]);     }          i = 0;     j = 0;     let ans = 0;     lMin = arr[0];          while (i < n && j < n) {                  // Compare with answer and increment j.         if (lMin <= rMax[j]) {             ans = Math.max(ans, j - i);             j++;         }                  // Else, increment i.         else {             i++;             if (i + 1 < n)                  lMin = Math.min(lMin, arr[i]);         }     }          return ans; }  let arr = [34, 8, 10, 3, 2, 80, 30, 33, 1]; console.log(maxIndexDiff(arr)); 

Output
6

[Expected Approach - 3] Using Stack - O(n) time and O(n) space

The idea is to use a stack to maintain indices of potential minimum elements from left to right, then traverse the array from right to left to find the maximum index difference. By carefully managing the stack and comparing elements, we can efficiently identify the largest valid j-i difference where arr[i] <= arr[j].

Step by step approach:

  1. Create a stack of indices that maintains elements in increasing order from top to bottom. Push indices to stack only when the current element is smaller than the top of stack.
  2. Traverse the array from right to left:
    • For each right element, compare with stack top and update maximum difference.
  3. Pop stack elements that satisfy the condition to find optimal index differences.
C++
// C++ program to find the maximum // j - i such that arr[i] <= arr[j] #include <bits/stdc++.h> using namespace std;  int maxIndexDiff(vector<int>& arr) {     int n = arr.size();     stack<int> st;          // Maintain increasing (value-wise)      // indices from bottom to top     for (int i = 0; i < n; i++) {                  // Push only if stack is empty          // or current element is smaller          if (st.empty() || arr[st.top()] > arr[i]) {             st.push(i);         }     }      int ans = 0;          // Traverse array from right to left     for (int j = n - 1; j >= 0; j--) {                  // While stack is not empty and current right element          // is greater than or equal to stack top's element         while (!st.empty() && arr[st.top()] <= arr[j]) {                          // Update max difference             ans = max(ans, j - st.top());             st.pop();         }     }          return ans; }  int main() {     vector<int> arr = {34, 8, 10, 3, 2, 80, 30, 33, 1};     cout << maxIndexDiff(arr);     return 0; } 
Java
// Java program to find the maximum // j - i such that arr[i] <= arr[j] import java.util.*;  class GfG {      static int maxIndexDiff(int[] arr) {         int n = arr.length;         Stack<Integer> st = new Stack<>();          // Maintain increasing (value-wise)          // indices from bottom to top         for (int i = 0; i < n; i++) {              // Push only if stack is empty              // or current element is smaller              if (st.isEmpty() || arr[st.peek()] > arr[i]) {                 st.push(i);             }         }          int ans = 0;          // Traverse array from right to left         for (int j = n - 1; j >= 0; j--) {              // While stack is not empty and current right element              // is greater than or equal to stack top's element             while (!st.isEmpty() && arr[st.peek()] <= arr[j]) {                  // Update max difference                 ans = Math.max(ans, j - st.peek());                 st.pop();             }         }          return ans;     }      public static void main(String[] args) {         int[] arr = {34, 8, 10, 3, 2, 80, 30, 33, 1};         System.out.println(maxIndexDiff(arr));     } } 
Python
# Python program to find the maximum # j - i such that arr[i] <= arr[j]  def maxIndexDiff(arr):     n = len(arr)     st = []      # Maintain increasing (value-wise)      # indices from bottom to top     for i in range(n):          # Push only if stack is empty          # or current element is smaller          if not st or arr[st[-1]] > arr[i]:             st.append(i)      ans = 0      # Traverse array from right to left     for j in range(n - 1, -1, -1):          # While stack is not empty and current right element          # is greater than or equal to stack top's element         while st and arr[st[-1]] <= arr[j]:              # Update max difference             ans = max(ans, j - st[-1])             st.pop()      return ans  if __name__ == "__main__":     arr = [34, 8, 10, 3, 2, 80, 30, 33, 1]     print(maxIndexDiff(arr)) 
C#
// C# program to find the maximum // j - i such that arr[i] <= arr[j] using System; using System.Collections.Generic;  class GfG {      static int maxIndexDiff(int[] arr) {         int n = arr.Length;         Stack<int> st = new Stack<int>();          // Maintain increasing (value-wise)          // indices from bottom to top         for (int i = 0; i < n; i++) {              // Push only if stack is empty              // or current element is smaller              if (st.Count == 0 || arr[st.Peek()] > arr[i]) {                 st.Push(i);             }         }          int ans = 0;          // Traverse array from right to left         for (int j = n - 1; j >= 0; j--) {              // While stack is not empty and current right element              // is greater than or equal to stack top's element             while (st.Count > 0 && arr[st.Peek()] <= arr[j]) {                  // Update max difference                 ans = Math.Max(ans, j - st.Peek());                 st.Pop();             }         }          return ans;     }      static void Main() {         int[] arr = {34, 8, 10, 3, 2, 80, 30, 33, 1};         Console.WriteLine(maxIndexDiff(arr));     } } 
JavaScript
// JavaScript program to find the maximum // j - i such that arr[i] <= arr[j]  function maxIndexDiff(arr) {     let n = arr.length;     let st = [];      // Maintain increasing (value-wise)      // indices from bottom to top     for (let i = 0; i < n; i++) {          // Push only if stack is empty          // or current element is smaller          if (st.length === 0 || arr[st[st.length - 1]] > arr[i]) {             st.push(i);         }     }      let ans = 0;      // Traverse array from right to left     for (let j = n - 1; j >= 0; j--) {          // While stack is not empty and current right element          // is greater than or equal to stack top's element         while (st.length > 0 && arr[st[st.length - 1]] <= arr[j]) {              // Update max difference             ans = Math.max(ans, j - st[st.length - 1]);             st.pop();         }     }      return ans; }  let arr = [34, 8, 10, 3, 2, 80, 30, 33, 1]; console.log(maxIndexDiff(arr)); 

Output
6

Next Article
Maximum j - i in an array such that arr[i] <= arr[j]

K

kartik
Improve
Article Tags :
  • DSA
  • Arrays
  • Amazon
  • Snapdeal
Practice Tags :
  • Amazon
  • Snapdeal
  • Arrays

Similar Reads

    Maximize value of (arr[i] - i) - (arr[j] - j) in an array
    Given an array, arr[] find the maximum value of (arr[i] - i) - (arr[j] - j) where i is not equal to j. Where i and j vary from 0 to n-1 and n is size of input array arr[]. Examples: Input : arr[] = {9, 15, 4, 12, 13} Output : 12 We get the maximum value for i = 1 and j = 2 (15 - 1) - (4 - 2) = 12 In
    10 min read
    Find Maximum value of abs(i - j) * min(arr[i], arr[j]) in an array arr[]
    Given an array of n distinct elements. Find the maximum of product of Minimum of two numbers in the array and absolute difference of their positions, i.e., find maximum value of abs(i - j) * min(arr[i], arr[j]) where i and j vary from 0 to n-1. Examples : Input : arr[] = {3, 2, 1, 4} Output: 9 // ar
    6 min read
    Maximize arr[j] - arr[i] + arr[l] - arr[k], such that i < j < k < l
    Maximize arr[j] - arr[i] + arr[l] - arr[k], such that i < j < k < l. Find the maximum value of arr[j] - arr[i] + arr[l] - arr[k], such that i < j < k < l Example: Let us say our array is {4, 8, 9, 2, 20} Then the maximum such value is 23 (9 - 4 + 20 - 2)Recommended PracticeMaximum
    11 min read
    Maximum value of arr[i] + arr[j] + i – j for any pair of an array
    Given an array arr[] consisting of N integers, the task is to find the maximum value of (arr[i] + arr[j] + i ? j) for any possible pair (i, j) of the given array. Examples: Input: arr[] = {1, 9, 3, 6, 5}Output: 13Explanation:The pair of the array having the maximum value of (arr[i] + arr[j] + i ? j)
    9 min read
    Rearrange an array such that arr[i] = i
    Given an array of elements of length n, ranging from 0 to n - 1. All elements may not be present in the array. If the element is not present then there will be -1 present in the array. Rearrange the array such that arr[i] = i and if i is not present, display -1 at that place.Examples: Input: arr[] =
    13 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences