Subsequence with longest monotonic increasing

Source: Internet
Author: User

Subsequence with longest monotonic increasing

Subsequence with longest monotonic increasing

Question: design an O (n ^ 2) complexity algorithm to find the longest monotonic increasing subsequence of a sequence composed of n numbers.


Import java. util. extends; public class Main {public static void main (String [] args) {extends = new loads (System. in); while (partial. hasNext () {int n = seconds. nextInt (); int [] nums = new int [n + 1]; // number of series data int [] sub_len = new int [n + 1]; // sub_len [I] indicates the length of the longest ascending sequence from I to n int [] sub_index = new int [n + 1]; // sub_index [I] indicates the subscript for (int I = 1; I <= n; I ++) {nums [I] = numeric. nextInt (); sub_l En [I] = 1; sub_index [I] = 0;} for (int I = n-1; I> = 1; I --) {int max = 0, p = 0; // temporary variable for (int j = I + 1; j <= n; j ++) {if (nums [I] <nums [j] & sub_len [j]> max) {max = sub_len [j]; p = j ;}if (p! = 0) {sub_len [I] = sub_len [p] + 1; sub_index [I] = p ;}} int max = 0, p = 0; for (int I = 1; I <= n; I ++) {if (sub_len [I]> max) {max = sub_len [I]; p = I ;}} system. out. println ("maximum length:" + max); System. out. print ("Longest ascending sequence:"); while (p! = 0) {System. out. print (nums [p] + ""); p = sub_index [p];} System. out. println ();} bytes. close ();}}

Related Article

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.