http://www.geeksforgeeks.org/given-an-array-arr-find-the-maximum-j-i-such-that-arrj-arri/
1 #include <iostream> 2 #include <vector> 3 #include <algorithm> 4 #include <queue> 5 #include <stack> 6 #include <string> 7 #include <fstream> 8 #include <map> 9 using namespace std; 10 11 int maxindexdiff(int arr[], int n) { 12 vector<int> L(n), R(n); 13 L[0] = arr[0]; 14 for (int i = 1; i < n; i++) L[i] = min(L[i-1], arr[i]); 15 R[n-1] = arr[n-1]; 16 for (int i = n-2; i >= 0; i--) R[i] = max(R[i+1], arr[i]); 17 int left, right, ans; 18 left = right = 0; 19 ans = -1; 20 while (left < n && right < n) { 21 if (L[left] < R[right]) { 22 ans = max(ans, right - left); 23 right++; 24 } 25 else left++; 26 } 27 return ans; 28 } 29 30 int main() { 31 int arr[10] = {9, 2, 3, 4, 5, 6, 7, 8, 18, 0}; 32 cout << maxindexdiff(arr, 10) << endl; 33 return 0; 34 }