Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simpest way to get the longest sequence of sorted elements from a given unsorted integer vector in c++

I have an unsorted array and need to extract the longest sequence of sorted elements. For instance

A = 2,4,1,7,4,5,0,8,65,4,2,34

here 0,8,65 is my target sequence

I need to keep track of the index where this sequence starts

like image 209
JackNova Avatar asked Aug 19 '12 12:08

JackNova


People also ask

How do you find the longest array sequence?

A simple solution is to use two nested loops. In the outer loop, we look for positive elements. In the inner loop, we count number of positives starting with the positive element picked by outer loop. Time complexity of this solution is O(n^2).

How do you find the largest and smallest number in an unsorted integer array?

Iterate over the array and compare if the current element is greater than the maxi or less than the mini. Update the mini/maxi element with the current element so that the minimum/maximum element is stored in the mini/maxi variable. Return the mini/maxi variable.


1 Answers

You can do it in linear time O(N) with this algorithm: construct vector len of the same size N as the original vector, such that len[i] contains the length of the longest consecutive ascending run to which element seq[i] belongs.

The value of len[i] can be calculated as follows:

len[0] = 1;
for (int i = 1 ; i != N ; i++) {
    len[i] = seq[i-1] >= seq[i] ? 1 : len[i-1]+1;
}

With len in hand, find the index of max(len) element. This is the last element of your run. Track back to len[j] == 1 to find the initial element of the run.

seq    len
---    ---
  2      1
  4      2
  1      1
  7      2
  4      1
  5      2
  0      1
  8      2
 65      3 << MAX
  4      1
  2      1
 34      2

Note that at each step of the algorithm you need only the element len[i-1] to calculate len, so you can optimize for constant space by dropping vector representation of len and keeping the prior one, the max_len, and max_len_index.

Here is this algorithm optimized for constant space. Variable len represents len[i-1] from the linear-space algorithm.

int len = 1, pos = 0, maxlen = 1, current_start = 0;
for (int i = 1 ; i < seq.size() ; i++) {
    if (seq[i] > seq[i-1]) {
        len++;
        if (len > maxlen) {
            maxlen = len;
            pos = current_start;
        }
    } else {
        len = 1;
        current_start = i;
    }
}

Here is a link to this program on ideone.

like image 78
Sergey Kalinichenko Avatar answered Sep 20 '22 15:09

Sergey Kalinichenko