Created
January 9, 2018 02:27
-
-
Save jack5241027/7e4280f7acee98504143292a03535965 to your computer and use it in GitHub Desktop.
322. Coin Change - Greedy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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