Guest User

Untitled

a guest
Jan 17th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.74 KB | None | 0 0
  1. const helper = (ary, amount) => {
  2. const res = 0;
  3. let current = ary.pop();
  4. let left = amount;
  5. let done = false;
  6. let count = 0;
  7.  
  8. while (current && !done) {
  9. const nextLeft = left - current;
  10. if (nextLeft < 0) {
  11. current = ary.pop();
  12. } else if (nextLeft > 0) {
  13. count += 1;
  14. left = nextLeft;
  15. } else {
  16. count += 1;
  17. done = true;
  18. }
  19. }
  20.  
  21. return done ? count : res;
  22. }
  23.  
  24. var coinChange = function (coins, amount) {
  25. if (!amount) return 0;
  26. coins.sort((a, b) => a - b);
  27. const length = coins.length;
  28. let res = Infinity;
  29.  
  30. for (let i = length; i >= 0; i--) {
  31. const ans = helper(coins.slice(0, i), amount);
  32. if (ans && ans < res) {
  33. res = ans;
  34. }
  35. }
  36.  
  37. return res === Infinity ? -1 : res;
  38. };
Add Comment
Please, Sign In to add comment