/* Max Distance */
/*
Given an array arr[], find the maximum j – i such that arr[i] <= arr[j]
*/
/*
Given an array arr[], find the maximum j – i such that arr[i] <= arr[j]
*/
#include <iostream>
using namespace std;
int maxIndexDiff(int *arr, int n){
if(n <= 1)
return 0;
int *leftMin = new int[n];
int *rightMax = new int[n];
leftMin[0] = arr[0];
rightMax[n - 1] = arr[n - 1];
for(int i = 1; i < n; i++){
if(arr[i] < leftMin[i - 1]){
leftMin[i] = arr[i];
}else{
leftMin[i] = leftMin[i - 1];
}
}
for(int i = n - 2; i >= 0; i--){
if(arr[i] > rightMax[i + 1]){
rightMax[i] = arr[i];
}else{
rightMax[i] = rightMax[i + 1];
}
}
int i = 0, j = 0, maxDiff = -1;
while(i < n && j < n){
if(leftMin[i] <= rightMax[j]){
maxDiff = max(maxDiff, j - i);
j++;
}else{
i++;
}
}
return maxDiff;
}
int main(){
int arr[] = {19, 2, 3, 4, 5, 6, 7, 8, 1, 0};
int n = sizeof(arr)/sizeof(arr[0]);
int maxDiff = maxIndexDiff(arr, n);
cout << maxDiff << endl;
return 0;
}
0 comments:
Post a Comment