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)