forked from Masked-coder11/gfg-POTD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
05..03.2024.cpp
38 lines (34 loc) · 828 Bytes
/
05..03.2024.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution{
public:
// A[]: input array
// N: size of array
// Function to find the maximum index difference.
int maxIndexDiff(int a[], int n)
{
// Your code here
vector<int>preMin(n,0);
vector<int>suffMax(n,0);
int maxi=a[n-1];
for(int i=n-1;i>=0;i--){
maxi=max(maxi, a[i]);
suffMax[i]=maxi;
}
int mini=a[0];
for(int i=0;i<n;i++){
mini=min(mini, a[i]);
preMin[i]=mini;
}
int i=0, j=0;
int ans=-1;
while(i<n && j<n){
if(preMin[i]<=suffMax[j]){
ans=max(ans, j-i);
j++;
}
else{
i++;
}
}
return ans;
}
};