A Distance Maximizing Problem

Given an array A of integers, find the maximum of j-i subjected to the constraint of A[i] < A[j].

Sponsored: https://www.wanderful.io has published a chatbot, who can chat with you and help you find apartments in San Francisco and Bay area. Check it out: http://m.me/wanderful.io


1. Start point should have no left point that is smaller.

2. End point should have no right point that is larger.

3. Scan array once from left to right. Find the current min from left.

4. For the smallest element with index i, find rightest feasible index j such that A[j]>A[i].

5. Search for next current min i, find rightest feasible index j such that A[j]>A[i] starting from the last stop point(We can ignore the right part).

01 int dist_max(int A[], int n, int &start, int &end)
02 {
03     bool *min_left=new bool [n];
05     int min=A[0];
06     min_left[0]=true;
07     for(int i=1;i<n;i++){
08         if(A[i]<min){
09             min_left[i]=true;
10             min=A[i];
11         }else{
12             min_left[i]=false;
13         }
14     }
16     int max_dist=0;
17     int i=n1;
18     int j=n1;
19     while(i>=0){
20         if(min_left[i]==false){
21             i;
22             continue;
23         }
24         while((A[j]<=A[i])&&(j>i))
25             j;
26         if((ji)>max_dist){
27             max_dist=ji;
28             start=i;
29             end=j;
30         }
31         i;
32     }
33     return max_dist;
34 }
This entry was posted in Array and linked list. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s