Advertisement
Guest User

Untitled

a guest
Sep 21st, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. var maxEnvelopes = function(envelopes) {
  2. var count = 0;
  3. if (envelopes.length === 0) { return count; }
  4. count++;
  5. if (envelopes.length === 1) { return count; }
  6. //sort by width of each envelope, sort by heigth of each envelope for matching widths
  7. envelopes.sort((a, b) => {
  8. if (a[0] < b[0]) {
  9. return -1;
  10. }
  11. if (a[0] > b[0]) {
  12. return 1;
  13. }
  14. if (a[0] === b[0]) {
  15. if (a[1] < b[1]) {
  16. return -1;
  17. }
  18. if (a[1] > b[1]) {
  19. return 1;
  20. }
  21. if (a[1] === b[1]) {
  22. return 0;
  23. }
  24. }
  25. })
  26. //check in order of envelopes for next width that is >
  27. //then compare height too
  28. //if yes, count++ and reset the item to check against
  29.  
  30. var current_item = envelopes[0];
  31.  
  32. for (var i = 1; i < envelopes.length; i++) {
  33. if (envelopes[i][0] > current_item[0]) {
  34. if (envelopes[i][1] > current_item[1]) {
  35. count++;
  36. current_item = envelopes[i];
  37. }
  38. }
  39. }
  40. return count;
  41. };
  42.  
  43. //recursion needed but didn't get this working
  44. // var recurse = function(envelopes) {
  45. // //base case, reach end of envelopes and return 0 or 1 based on size
  46. // //recurse case, test for each item in the array
  47. // //if match, then recurse with the rest of the array, count + return
  48.  
  49. // var count = 0;
  50. // if (envelopes.length === 0) { return count; }
  51. // count++;
  52. // if (envelopes.length === 1) { return count; }
  53. // var current_item = envelopes[0];
  54. // var maxCount = count;
  55.  
  56. // for (var i = 1; i < envelopes.length; i++) {
  57. // if (envelopes[i][0] > current_item[0]) {
  58. // if (envelopes[i][1] > current_item[1]) {
  59. // count += recurse(envelopes.slice(i));
  60. // }
  61. // }
  62. // if (count > maxCount) {
  63. // maxCount = count;
  64. // }
  65. // }
  66. // return maxCount;
  67. // }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement