Length of the longest non-ascending sub-sequence

Source: Internet
Author: User

The longest non-ascending sub-sequence problem is a classic DP problem. A complete description of the problem is given below:

Give you a bunch of sequence a1,a2,a3,a4,a5 ... An. Let you find out one of its oldest firstborn sequences s1,s2,s3,s4 ... Sm. Make S1<=S2<=S3<=S4.........<=SM.

From the problem description, we can change the <= into the longest non-descending sub-sequence by exchanging various other relationship symbols, all of which are just the same as the relationship description. Now, let's just summarize the longest non-ascending subsequence problem to apply to other types.

Since this is a classic DP problem, it is clearly necessary to find out his state transfer equation. First, we use dp[i] to represent the length of the longest non-ascending subsequence of 1--i. Then Dp[i]=max (Dp[j]) +1,j∈[1, I-1]. Apparently dp[1]=1. So go on, oh, just start with the second entry.

The algorithm is described as follows:

1.DP[1] = 1;

2. This iterates through the entire sequence, finding the oldest sequence length from the first item to the current item at a time.

3. Finding the largest of the DP arrays is the oldest sequence length of the entire sequence.

The algorithm complexity is: O (n^2)

1 intNum[n];2 intDp[n];3 4 intLis (intN)5 {6Memset (DP,0,sizeofDP);7     intans;8dp[0] =1;9      for(intI=1; i<n; i++)Ten     { OneAns =Dp[i]; A          for(intj=0; j<i; J + +) -             if(Num[i] <= num[j] && dp[j]>ans) -Ans =Dp[j]; theDp[i] = ans+1; -     } -Ans =0; -      for(intI=0; i<n; i++) +         if(Dp[i] >ans) -Ans =Dp[i]; +     returnans; A}

Length of the longest non-ascending sub-sequence

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.