SvetlanPetrova

LongestIncreasingSubsequence SoftUni

Jun 16th, 2021
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.util.Scanner;
  2. class LongestSequence {
  3. public static void main (String[] args) throws java.lang.Exception {
  4. Scanner sc = new Scanner(System.in);
  5. String[] array1 = sc.nextLine().split(" ");
  6. int[] numbers = new int[array1.length];
  7. for(int i = 0; i < array1.length; i ++){
  8. numbers[i] = Integer.parseInt(array1[i]);
  9. }
  10. int maxLength = 0;
  11. int lastIndex = -1;
  12. int[] len = new int[numbers.length];
  13. int[] previous = new int[numbers.length];
  14.  
  15. for (int i = 0; i < numbers.length; i++) {
  16. len[i] = 1;
  17. previous[i] = -1;
  18.  
  19. for (int k = 0; k < i; k++) {
  20. if (numbers[k] < numbers[i] && len[k] + 1 > len[i]) {
  21. len[i] = len[k] + 1;
  22. previous[i] = k;
  23. }
  24. }
  25.  
  26. if (len[i] > maxLength) {
  27. maxLength = len[i];
  28. lastIndex = i;
  29. }
  30. }
  31.  
  32. int[] lis = new int[maxLength];
  33. int currentIndex = maxLength - 1;
  34.  
  35. while (lastIndex != -1) {
  36. lis[currentIndex] = numbers[lastIndex];
  37. currentIndex--;
  38. lastIndex = previous[lastIndex];
  39. }
  40. for(int print = 0; print < lis.length; print++){
  41. System.out.print(lis[print] + " ");
  42. }
  43. }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment