Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const helper = (ary, amount) => {
- const res = 0;
- let current = ary.pop();
- let left = amount;
- let done = false;
- let count = 0;
- while (current && !done) {
- const nextLeft = left - current;
- if (nextLeft < 0) {
- current = ary.pop();
- } else if (nextLeft > 0) {
- count += 1;
- left = nextLeft;
- } else {
- count += 1;
- done = true;
- }
- }
- return done ? count : res;
- }
- var coinChange = function (coins, amount) {
- if (!amount) return 0;
- coins.sort((a, b) => a - b);
- const length = coins.length;
- let res = Infinity;
- for (let i = length; i >= 0; i--) {
- const ans = helper(coins.slice(0, i), amount);
- if (ans && ans < res) {
- res = ans;
- }
- }
- return res === Infinity ? -1 : res;
- };
Add Comment
Please, Sign In to add comment