Not a member of GistPad yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- // idea : create a new array say 'arr' which has sorted and unique elements from original array
- // find LCS between two arrays
- public int lengthOfLIS(int[] nums) {
- int n = nums.length;
- // store the original array into hashset to ignore the duplicates
- Set<Integer> set = new HashSet<>();
- for(int ele : nums)
- set.add(ele);
- // sort the elements in hashset by storing into array list
- List<Integer> arr = new ArrayList<>();
- arr.addAll(set);
- int m = arr.size();
- // create a matrix
- int[][] t = new int[n+1][m+1];
- // intialise the matrix with base condition
- for(int i=0; i<n+1; i++)
- {
- for(int j=0; j<m+1; j++)
- {
- if(i == 0 || j == 0)
- t[i][j] = 0;
- }
- }
- // same as LCS
- for(int i=1; i<n+1; i++)
- {
- for(int j=1; j<m+1; j++)
- {
- if(nums[i-1] == arr.get(j-1))
- {
- t[i][j] = 1 + t[i-1][j-1];
- }
- else
- }
- }
- return t[n][m];
- }
- }
RAW Paste Data
Copied
