-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMaximumIndex.cpp
More file actions
36 lines (35 loc) · 809 Bytes
/
Copy pathMaximumIndex.cpp
File metadata and controls
36 lines (35 loc) · 809 Bytes
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
class Solution{
public:
// A[]: input array
// N: size of array
// Function to find the maximum index difference.
int maxIndexDiff(int a[], int n)
{
stack<int> st;
for(int i = n - 1; i >= 0; i--)
{
if(st.empty() || a[st.top()] < a[i])
{
st.push(i);
}
}
int ans = 0;
int i = 0;
while(i < n && !st.empty())
{
if(a[i] <= a[st.top()] && i <= st.top())
{
ans = max(ans, st.top() - i);
st.pop();
}
else if(i > st.top())
{
st.pop();
}
else
{
i++;
}
}
return ans;
}