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 maximumInput: [6, 5, 4, 3, 2, 1]
Output: 0
Explanation: Take any i and j where i == j.
Table of Content
- [Naive Approach] Using Two Nested Loops - O(n^2) time and O(1) space
- [Expected Approach - 1] Using Precomputed Min Max Values - O(n) time and O(n) space
- [Expected Approach - 2] Using Precomputed Max (or Min) Array - O(n) time and O(n) space
- [Expected Approach - 3] Using Stack - O(n) time and O(n) space
[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 indicesjandiand keep track of the maximum difference found.
// 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 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 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# 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 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
[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:
- Precompute the minimum values from left to right for each position.
- Precompute the maximum values from right to left for each position.
- Use two pointers starting at the beginning of both arrays.
- When the minimum value is less than or equal to maximum value, record the distance and move right pointer.
- 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]:
- First we build lMin array (minimum values from left to right):
- [34, 8, 8, 3, 2, 2, 2, 2, 1]
- Then we build rMax array (maximum values from right to left):
- [80, 80, 80, 80, 80, 80, 33, 33, 1]
- Starting with i=0, j=0: lMin[0]=34, rMax[0]=80,
- condition is satisfied (34≤80), record diff=0, increment j
- At i=0, j=5: lMin[0]=34, rMax[5]=80, max diff=5,
- increment j
- Continue until i=1, j=8: lMin[1]=8, rMax[8]=1,
- condition fails (8>1), increment i
- At i=4, j=7: lMin[4]=2, rMax[7]=33,
- condition satisfied (2≤33), max diff=3, increment j
- 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++ 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 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 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# 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 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++ 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 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 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# 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 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:
- 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.
- Traverse the array from right to left:
- For each right element, compare with stack top and update maximum difference.
- Pop stack elements that satisfy the condition to find optimal index differences.
// 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 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 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# 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 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