Guest User

Untitled

a guest
Jan 17th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.64 KB | None | 0 0
  1. var coinChange = function (coins, amount) {
  2. if (!amount) return amount;
  3.  
  4. let smallest = Infinity;
  5.  
  6. const helper = (val, path) => {
  7. for (let i = 0; i < coins.length; i++) {
  8. const nextVal = val + coins[i];
  9. if (nextVal < amount) {
  10. helper(nextVal, path.concat(coins[i]));
  11. } else if (nextVal === amount) {
  12. if ((path.length + 1) < smallest) {
  13. smallest = path.length + 1;
  14. }
  15. }
  16. }
  17. };
  18.  
  19. for (let i = 0; i < coins.length; i++) {
  20. if (coins[i] === amount) {
  21. smallest = 1;
  22. } else {
  23. helper(coins[i], [coins[i]]);
  24. }
  25. }
  26.  
  27. return smallest === Infinity ? -1 : smallest;
  28. };
Add Comment
Please, Sign In to add comment