[Geeks for Geeks] Maximum Index

Maximum Index

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].

  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution{
public:
int maxIndexDiff(int arr[], int n) {
vector<int> midp(n), madp(n);
for(int i = 0, mi = INT_MAX; i < n; i++) {
mi = min(mi, arr[i]);
midp[i] = mi;
}
for(int i = n - 1, ma = INT_MIN; i >= 0; i--) {
ma = max(ma, arr[i]);
madp[i] = ma;
}
int i = 0, j = 0, res = 0;
while(i < n and j < n) {
if(midp[i] <= madp[j]) {
res = max(res, j - i);
j++;
} else i++;
}
return res;
}

};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/15/PS/GeeksforGeeks/maximum-index_2/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.