The longest ascending subsequence in the array (Dynamic planning problem)

Source: Internet
Author: User

The longest increasing subsequence (LIS)
Given a sequence, find the longest subsequence of the sequence so that all the elements of the subsequence are ascending, and the relative positions between the elements are constant (the elements can be nonadjacent in the original array, but the relative position remains the same)
For example, LIS for {10, 22, 9, 33, 21, 50, 41, 60, 80} are 6,lis {10, 22, 33, 50, 60, 80}.

Analysis
ARR[0...N-1] is the input, then L (i) is the length of the LIS to the element I, that is, Arr[i] as the last element of the LIS when the length of the LIS, then with the recursive form L (i) can be written:

 for (j<i)     if (Arr[j]<arr[i]) L (i) = {1+if// recursive termination condition    L (i) = 1

So this problem can be broken down into subproblems and solved by recursion:

#include <iostream>using namespacestd;intLIS (int*arr,intNint*max_ref) {  if(n==1)return 1; intRes, longest_here=1;  for(inti =1; i<n; ++i) {res=LIS (arr, I, max_ref); if(arr[i-1]<arr[n-1] && res+1>longest_here) Longest_here= res+1; }  if(*max_ref <longest_here)*max_ref =Longest_here; returnLongest_here;}intMain () {intArr[] = {Ten, A,9, -, +, -, A, - }; intn =sizeof(arr)/sizeof(arr[0]); intmax=1; LIS (arr, N,&max); cout<<max<<Endl; return 0;}

Non-recursive method, this need to open up additional storage space.

intLIS2 (int*arr,intN) {  int*longest_here =New int[n] (); longest_here[0] =1; intMax =1;  for(inti =1; i<n; ++i) { for(intj =0; j<i; ++j) {if(Arr[j]<arr[i] && longest_here[j]+1>Longest_here[i]) longest_here[i]= longest_here[j]+1; }    if(longest_here[i]>max) Max=Longest_here[i]; }  Delete[]longest_here; returnMax;}

A solution with Time complexity O (Nlog (n)) at the top of the wiki

The longest ascending subsequence in the array (Dynamic planning problem)

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.