Advertisement
Deianov

04. Longest Increasing Subsequence

Feb 10th, 2019
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.18 KB | None | 0 0
  1. // 04. Longest Increasing Subsequence
  2.  
  3. package MoreExercise;
  4.  
  5. import java.util.Arrays;
  6. import java.util.Scanner;
  7.  
  8. public class M04 {
  9.     public static void main(String[] args) {
  10.         Scanner scanner = new Scanner(System.in);
  11.         int[] nums = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
  12.         int length = nums.length;
  13.         int[] lens = new int[length];
  14.         String[] subSequences  = new String[length];
  15.         for (int i = 0; i < length ; i++) {
  16.             lens[i] = 1;
  17.             subSequences [i] = "" + nums[i];
  18.             for (int j = 0; j < i ; j++) {
  19.                 if (nums[i] > nums[j]) {
  20.                     if (lens[j] + 1 > lens[i]) {
  21.                         lens[i] = lens[j] + 1;
  22.                         subSequences[i] = subSequences[j] + " " + nums[i];
  23.                     }
  24.                 }
  25.             }
  26.         }
  27.         int maxIndex = -1;
  28.         int maxLen = -1;
  29.         for (int i = 0; i < length ; i++) {
  30.             if (lens[i] > maxLen) {
  31.                 maxLen = lens[i];
  32.                 maxIndex = i;
  33.             }
  34.         }
  35.         System.out.println(subSequences[maxIndex]);
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement