Solving DSA

I was trying to solve some DSA problems today I solved total 5 problems 4 easy and 1 medium on GFG portal the medium the problem messed my brain.
At first I thought it was easy but after trying to solve it felt like banging my head.

I tried solve on my own my brute force approach did work I failed with optimal one I took my friends help for that.

The problem is : Maximum Index

Given an array arr of positive integers. The task is to return the maximum of j - i subjected to the constraint of arr[i] < arr[j] and i < j.

Examples:

Input: arr[] = [1, 10]
Output: 1
Explanation: arr[0] < arr[1] so (j-i) is 1-0 = 1.

Here is the solution
int maxIndexDiff(int[] arr) {

int n = arr.length;
int [] lmin = new int[n];
int [] rmax = new int[n];
lmin[0] = arr[0];

for(int i = 1; i < n; i++) {
lmin[i] = Math.min(arr[i],lmin[i-1]);
}

rmax[n-1] = arr[n-1];
for(
int i = n-2; i >= 0; i--){
rmax[i] = Math.max(arr[i], rmax[i+1]);
}

int i = 0, j = 0, maxDiff = 0; while(i < n && j < n){
if(lmin[i] <= rmax[j]){
maxDiff = Math.max(maxDiff,j-i); j++;
} else{ i++; }
}return maxDiff;
}

1
Subscribe to my newsletter

Read articles from Raghavendra M Devale directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Raghavendra M Devale
Raghavendra M Devale