Question: Given an array A, for subscript I <j, there is a [I] <A [J], and the maximum value of J-I is obtained.
Ideas: First, traverse in a forward order, and use an auxiliary array to record the subscript of the minimum value in the sub-array on the left of each element. Then, traverse in reverse order to maintain two pointers, which are initially directed to the last element, move the two pointers to find the maximum distance.
Code:
1 # include <iostream> 2 # include <vector> 3 using namespace STD; 4 5 Int maxdist (INT num [], int N) 6 {7 if (n <2) 8 return 0; 9 10 vector <int> left_min_pos (n, 0); 11 int cur_min_pos = 0; 12 INT max_dist = 0; 13 14 for (INT I = 1; I <n; ++ I) 15 {16 if (Num [I] <num [cur_min_pos]) 17 {18 left_min_pos [I] = I; 19 cur_min_pos = I; 20} 21 else22 {23 left_min_pos [I] = cur_min_pos; 24} 25} 26 27 for (INT I = n-1, j = n-1; I> = 0 ;) // I <j28 {29 I = left_min_pos [I]; 30 31 if (Num [J]> = num [I]) // locate an ordered pair, or the same element 32 {33 If (J-I> max_dist) 34 {35 max_dist = J-I; 36} 37 -- I; // for the current I, J is already the farthest, so fix J, I walk to the left, find a larger j-i38} 39 else40 {41 -- J; // not an ordered pair, for J, the last I is already the farthest, with fixed I. J goes to the left 42} 43} 44 45 return max_dist; 46} 47 48 int main () 49 {50 const int n = 5; 51 int num [N] = {3, 6, 4, 1, 2}; 52 53 cout <maxdist (Num, n) <Endl; 54 55 return 0; 56}