/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
{
//int[] A={86,34, 8, 10, 3, 2, 80, 30, 33, 1};
//int[] A={9, 2, 3, 4, 5, 6, 7, 8, 18, 0};
//int[] A={1, 2, 3, 4, 5, 6};
//int[] A={6, 5, 4, 3, 2, 1};
//int[] A={1, 5, 4, 6, 10, 7, 8};
//int[] A={9, 2, 3, 4, 5, 6, 7, 18, 1, 0};
int[] A={99, 100 , 1, 2, 3, 4, 5, 6, 7};
System.
out.
print("Result max index is "+getMaxIndexDiff
(A
)); }
public static int getMaxIndexDiff(int[] A){
int max=0;
int i,j;
int[] stack=new int[A.length];
int top=-1;
j=A.length-1;
for(i=A.length-2;i>=0;i--){
if(A[i]>A[j]){
stack[++top]=j;
j=i;
}
}
i++;
if(j-i>max)
max=j-i;
i=0;
while(top>=0 && i<A.length){
if(A[i]<A[stack[top]]){
j=stack[top--];
if(j-i>max)
max=j-i;
}
else
i++;
}
return max;
}
}
LyogcGFja2FnZSB3aGF0ZXZlcjsgLy8gZG9uJ3QgcGxhY2UgcGFja2FnZSBuYW1lISAqLwoKaW1wb3J0IGphdmEudXRpbC4qOwppbXBvcnQgamF2YS5sYW5nLio7CmltcG9ydCBqYXZhLmlvLio7CgovKiBOYW1lIG9mIHRoZSBjbGFzcyBoYXMgdG8gYmUgIk1haW4iIG9ubHkgaWYgdGhlIGNsYXNzIGlzIHB1YmxpYy4gKi8KY2xhc3MgSWRlb25lCnsKCXB1YmxpYyBzdGF0aWMgdm9pZCBtYWluIChTdHJpbmdbXSBhcmdzKSB0aHJvd3MgamF2YS5sYW5nLkV4Y2VwdGlvbgoJewoJCS8vaW50W10gQT17ODYsMzQsIDgsIDEwLCAzLCAyLCA4MCwgMzAsIDMzLCAxfTsKCQkvL2ludFtdIEE9ezksIDIsIDMsIDQsIDUsIDYsIDcsIDgsIDE4LCAwfTsKCQkvL2ludFtdIEE9ezEsIDIsID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