"Difficult" to find the longest increment subsequence in an array, time complexity O (NLOGN)

Source: Internet
Author: User

Title: "The Beauty of programming" P194

Write a program that is as low in complexity as possible, and ask for the longest increment of the length of a subsequence in an array (length of elements).

Note that the subject thinks that the longest increment subsequence can have equal elements, such as (1,2,2,3,3,4,5,6).


The time complexity is O (n^2) The procedure idea is very simple, the reference book solution one. In order to improve the solution of O (n^2), we can reduce the complexity of time by using the binary search of ordered array. the crux of the problem is to create an array of length length+1 MINV, Minv[i] represents the minimum value of the largest element of the increment subsequence of length i. and the array Minv is ascending, which is especially important to understand.

Here is the code for the time Complexity O (NLOGN):

In ordered array minv, from subscript 1 to Endindex, look for the largest number in the number less than or equal to K, return its subscript//If all the numbers are greater than K, return -1int find_less_than_k (const int* Minv,const int Endindex,const int k) {int left=1,right=endindex,res=-1;while (left<=right) {int mid=left+ (right-left)/2;if (MinV[ mid]<=k) {res=mid;left=mid+1;} Elseright=mid-1;} return res;} int longest_increasing_subsequence (const int* arr,const int length) {if (Arr==nullptr | | length<=0) return-1;int* LIS= New int[length];int* minv=new int[length+1];for (int i=0;i<length;i++) {lis[i]=1; Minv[i]=int_max;} Minv[length]=int_max; Minv[1]=arr[0];int res=1,endindex=1;for (int i=1;i<length;i++) {int index=find_less_than_k (MinV,endindex,arr[i]) ; if (index!=-1) {lis[i]=index+1;if (lis[i]>res) {res=lis[i];endindex=res;}} if (Arr[i]<minv[lis[i]]) minv[lis[i]]=arr[i];} Delete[] minv;delete[] Lis;return Res;}


"Difficult" to find the longest increment subsequence in an array, time complexity O (NLOGN)

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.