[Geeks for Geeks] Maximum Index

Maximum Index

Given an array A[] of N positive integers. The task is to find the maximum of j - i subjected to the constraint of A[i] < A[j] and i < 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
class Solution{
public:
int maxIndexDiff(int A[], int N) {
int res = 0;
vector<int> mi(N), ma(N);
mi[0] = A[0], ma[N-1] = A[N-1];
for(int i = 1; i < N; i++)
mi[i] = min(mi[i-1], A[i]);
for(int i = N - 2; i >= 0; i--)
ma[i] = max(ma[i+1], A[i]);
int i = 0, j = 0;
while(i < N and j < N) {
if(mi[i] <= ma[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/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.