Guest User

Untitled

a guest
Nov 18th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. package com.abhishek.dojo;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Arrays;
  5. import java.util.Comparator;
  6. import java.util.Optional;
  7.  
  8. public class LongestIncreasingSubsequence {
  9.  
  10. public static void main(String[] args) {
  11. Integer[] target = longestIncreasingSubsequence(new int[] { 3, 0, 1, 4, 6, 0, 15, -1 });
  12. ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(target));
  13. Optional<Integer> max = list.stream().max(Comparator.naturalOrder());
  14. System.out.println("longest increasing sub: " + max.get().intValue());
  15. }
  16.  
  17. // approach
  18. // 1. create a blank array and initialize it with all 1s assuming each
  19. // element has longest subsequence of atleast 1
  20.  
  21. // 2. create two loops, outer loop with i starting from 1 and inner loop with
  22. // start with j till i-1
  23.  
  24. // 3. at every point compare if num[j] < num [i] and if so then longest
  25. // increasing subsequence at i is 1+ longest increaing subsquence at j
  26.  
  27. public static Integer[] longestIncreasingSubsequence(int[] nums) {
  28.  
  29. Integer[] subseq = new Integer[nums.length];
  30.  
  31. for (int i = 0; i < nums.length; i++) {
  32. subseq[i] = 1;
  33. }
  34.  
  35. for (int i = 1; i < nums.length; i++) {
  36. for (int j = 0; j < i; j++) {
  37. if (nums[j] < nums[i] && subseq[i] < (subseq[j] + 1)) {
  38. subseq[i] = subseq[j] + 1;
  39. }
  40. }
  41. }
  42.  
  43. return subseq;
  44. }
  45. }
Add Comment
Please, Sign In to add comment