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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can do it in linear time
O(N)with this algorithm: construct vectorlenof the same sizeNas the original vector, such thatlen[i]contains the length of the longest consecutive ascending run to which elementseq[i]belongs.The value of
len[i]can be calculated as follows:With
lenin hand, find the index ofmax(len)element. This is the last element of your run. Track back tolen[j] == 1to find the initial element of the run.Note that at each step of the algorithm you need only the element
len[i-1]to calculatelen, so you can optimize for constant space by dropping vector representation oflenand keeping the prior one, themax_len, andmax_len_index.Here is this algorithm optimized for constant space. Variable
lenrepresentslen[i-1]from the linear-space algorithm.Here is a link to this program on ideone.