Algorithm problem--the maximum distance of ordered pairs within an array

Source: Internet
Author: User

Transferred from: http://www.cnblogs.com/qieerbushejinshikelou/p/3916958.html

title : Given an array A, for subscript i < J, have a[i] < a[j], the maximum value of j-i.

idea : The first positive sequence traversal, using an auxiliary array, the left sub-array of each element to record the lowest value of the subscript, and then the reverse traversal, maintain two pointers, the initial point to the last element, by moving two pointers to find the maximum distance.

Learning : To solve the problem of high complexity of the algorithm, often can increase the auxiliary space, the auxiliary space has two ways, one way is to use Hashtable, another way is to record historical information, before the maximum Ah, before the minimum AH.

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 vector<int> left_min_pos (n, 0 ); int cur_min_pos = 0;12 int max_dist = 0;13 + for (int i = 1; i < n; ++i) {+-if (Num[i] & Lt Num[cur_min_pos]) (left_min_pos[i) = i;19 Cur_min_pos = i;20}21 Else [Left_min_pos[i] = cur_min_pos;24}25}26 for (int i = n-1, j = n-1; I ; = 0;         )//i < j28 {i = left_min_pos[i];30 if (num[j] >= num[i])//Find an ordered pair, or the same element 32             {j-i > max_dist) {max_dist = j-i;36}37            I.;            For the current I, J has been the furthest, so fixed j,i left, to find a larger j-i38}39 else40 {--j; Not ordered pairs, for J, the previous I is the furthest, fixed i,j left to go 42}43    }44 return max_dist;46}47, int main (), {53 const int n = 5;51 int Num[n] = {3, 6, 4, 1, 2};52 cout << maxDist (num, n) << endl;54 return 0;56}

Algorithm problem--the maximum distance of ordered pairs within an array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.