shriyanshi24jindal

Longest Increasing Subsequence

Mar 28th, 2026
7
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
Java 9.34 KB | None | 0 0
  1. class Solution {
  2. // idea : create a new array say 'arr' which has sorted and unique elements from original array
  3. // find LCS between two arrays
  4.  
  5. public int lengthOfLIS(int[] nums) {
  6. int n = nums.length;
  7.  
  8. // store the original array into hashset to ignore the duplicates
  9. Set<Integer> set = new HashSet<>();
  10. for(int ele : nums)
  11. set.add(ele);
  12.  
  13. // sort the elements in hashset by storing into array list
  14. List<Integer> arr = new ArrayList<>();
  15. arr.addAll(set);
  16. Collections.sort(arr);
  17.  
  18. int m = arr.size();
  19.  
  20. // create a matrix
  21. int[][] t = new int[n+1][m+1];
  22.  
  23. // intialise the matrix with base condition
  24. for(int i=0; i<n+1; i++)
  25. {
  26. for(int j=0; j<m+1; j++)
  27. {
  28. if(i == 0 || j == 0)
  29. t[i][j] = 0;
  30. }
  31. }
  32.  
  33. // same as LCS
  34. for(int i=1; i<n+1; i++)
  35. {
  36. for(int j=1; j<m+1; j++)
  37. {
  38. if(nums[i-1] == arr.get(j-1))
  39. {
  40. t[i][j] = 1 + t[i-1][j-1];
  41. }
  42. else
  43. t[i][j] = Math.max(t[i-1][j], t[i][j-1]);
  44. }
  45. }
  46.  
  47. return t[n][m];
  48. }
  49. }
RAW Paste Data Copied