Guest User

Untitled

a guest
Mar 19th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. function Pair(a, b) {
  2. this.firstElement = a;
  3. this.secondElement = b;
  4. }
  5.  
  6. function compareFirstElements(a, b) {
  7. if(a.firstElement < b.firstElement) {
  8. return -1;
  9. }
  10. if(a.firstElement > b.firstElement) {
  11. return 1;
  12. }
  13. return 0;
  14. }
  15.  
  16. function maximumLength(collection) {
  17. //sort pairs
  18. var sorted = collection.sort(compareFirstElements);
  19. //console.log(sorted);
  20.  
  21. var table = new Array(sorted.length);
  22. table[0] = 1;
  23.  
  24. //time complexity here is O(N^2) which can be reduced to O(N logN)
  25. for(var i = 1; i < sorted.length; i++) {
  26. table[i] = table[i - 1];
  27. for(var j = i - 1; j >= 0; j--) {
  28. if(sorted[j].secondElement < sorted[i].firstElement) {
  29. table[i] = Math.max(table[i], table[j] + 1);
  30. }
  31. }
  32. }
  33. //return last number in table which represents the max
  34. return table[sorted.length - 1];
  35. }
  36.  
  37. //create an array of pairs
  38. var pairA = new Pair(1, 2),
  39. pairB = new Pair(2, 3),
  40. pairC = new Pair(3, 4),
  41.  
  42. pairD = new Pair(5, 24),
  43. pairE = new Pair(39, 60),
  44. pairF = new Pair(15, 28),
  45. pairG = new Pair(27, 40),
  46. pairH = new Pair(50, 90),
  47.  
  48. pairCollection = [pairA, pairB, pairC ];
  49. //pairCollection = [pairD, pairE, pairF, pairG, pairH ];
  50.  
  51. var maxLength = maximumLength(pairCollection);
  52. console.log("Max Length is: ", maxLength);
Add Comment
Please, Sign In to add comment