Skip to content

Instantly share code, notes, and snippets.

@jack5241027
Created January 9, 2018 02:27
Show Gist options
  • Select an option

  • Save jack5241027/7e4280f7acee98504143292a03535965 to your computer and use it in GitHub Desktop.

Select an option

Save jack5241027/7e4280f7acee98504143292a03535965 to your computer and use it in GitHub Desktop.
322. Coin Change - Greedy
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;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment