Topic:
Given the sequence of n integers, the longest length of all non-descending subsequence is obtained. For example {a_n}=3,18,7,14,10,12,23,41,16,24, where 3,18,23,41 is a length of 4 not descending sub-sequence,
But 3,7,10,12,16,24 is a subsequence of length 6.
It is found that if a (i) >=a (i-1), the length of the longest non-descending sequence ending with a (i) should be the longest non-descending sequence ending with a (i-1) plus 1. If it is less than, then go forward from a (i-1) until a (i) >a (j) is satisfied, at which point
The longest non-descending sequence length is the length at the end of a (j) plus 1. Creates an array that records the longest-oldest sequence length at the end of each element, and the final output maximum value. Time Complexity of O (n^2)
Public classLongestnondescendantsequence { Public Static voidMain (string[] args) {int[] arr=New int[] {3,18,7,14,10,12,23,41,16,24}; LNS (arr); } Public Static voidLNS (int[] arr) { int[] A=New int[Arr.length]; intMax=0; //single element not descending subsequence length cannot be less than 1, initialized to 1 for(inti=0;i<arr.length;i++) A[i]=1; for(inti=1;i<arr.length;i++) { //if the current element is greater than the previous element, the length of the non-descending subsequence at the end of the current element plus 1 if(arr[i]>=arr[i-1]) A[i]=a[i]+a[i-1]; //Otherwise, the previous element looks for elements that are smaller than the current element, and the length of the non-descending subsequence that is found after the current element ends is a non-descending subsequence length that ends with the found element plus 1 Else { for(intj=i-1;j>=0;j--) { if(arr[j]<Arr[i]) {A[i]=a[j]+1; Break; } } } } //Maximum print length for(inti=0;i<a.length;i++) { if(a[i]>max) Max=A[i]; } System.out.print (max); }}
Print results
Dynamic planning _ Longest non-descending subsequence Java