fork(7) download
  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3.  
  4. /**
  5.  * Created by Shreyans on 4/16/2015
  6.  */
  7.  
  8. class LNG_INC_SUB//Longest Increasing Subsequence
  9. {
  10. public static void main(String[] args) throws Exception
  11. {
  12. System.out.println("Enter Numbers Separated by Spaces to find their LIS\n");
  13. String[] s1=br.readLine().split(" ");
  14. int n=s1.length;
  15. int[] a=new int[n];//Array actual of Numbers
  16. String []ls=new String[n];// Array of Strings to maintain LIS for every element
  17. for(int i=0;i<n;i++)
  18. {
  19. a[i]=Integer.parseInt(s1[i]);
  20. }
  21. int[]dp=new int[n];//Storing length of max subseq.
  22. int max=dp[0]=1;//Defaults
  23. String seq=ls[0]=s1[0];//Defaults
  24. for(int i=1;i<n;i++)
  25. {
  26. dp[i]=1;
  27. String x="";
  28. for(int j=i-1;j>=0;j--)
  29. {
  30. //First check if number at index j is less than num at i.
  31. // Second the length of that DP should be greater than dp[i]
  32. // -1 since dp of previous could also be one. So we compare the dp[i] as empty initially
  33. if(a[j]<a[i]&&dp[j]>dp[i]-1)
  34. {
  35. dp[i]=dp[j]+1;//Assigning temp length of LIS. There may come along a bigger LIS of a future a[j]
  36. x=ls[j];//Assigning temp LIS of a[j]. Will append a[i] later on
  37. }
  38. }
  39. x+=(" "+a[i]);
  40. ls[i]=x;
  41. if(dp[i]>max)
  42. {
  43. max=dp[i];
  44. seq=ls[i];
  45. }
  46. }
  47. System.out.println("Length of LIS is: " + max + "\nThe Sequence is: " + seq);
  48. }
  49. }
Success #stdin #stdout 0.1s 320256KB
stdin
10 22 9 33 21 50 41 60 80
stdout
Enter Numbers Separated by Spaces to find their LIS

Length of LIS is: 6
The Sequence is: 10 22 33 41 60 80