Medium Dynamic Programming

Coin Change

Receives an array of coin denominations and a target amount, and returns the minimum number of coins needed to make that amount, or -1 if it cannot be made with the given coins. It solves this with bottom-up dynamic programming: a table dp[0..amount] tracks the minimum coins needed for every amount from 0 up to the target, seeded with the base case dp[0] = 0. For each amount i from 1 to the target, it tries every coin denomination no larger than i — if using that coin (dp[i - coin] + 1) needs fewer coins than the best found so far for i, dp[i] is updated. Returns dp[amount], or -1 if it stayed unreachable (no combination of the given coins sums exactly to the target).

Visualization

Input

Algorithm code

Custom input

Saved inputs

References