> For the complete documentation index, see [llms.txt](https://ucan.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ucan.gitbook.io/notes/dynamic-programming/322.-coin-change.md).

# 322. Coin Change

[You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return `-1`.](https://leetcode.com/problems/coin-change/)

{% hint style="info" %}
dynamic programming, iteration
{% endhint %}

```java
class Solution {
    public int coinChange(int[] coins, int amount) {
        int[] memo = new int[amount+1];
        for (int i=1; i<=amount; i++){
            for(int coin : coins){
                // check the conis in previous amounts
                if (i-coin>=0 && memo[i-coin]!=-1){
                    memo[i]= memo[i]>0? Math.min(memo[i], memo[i-coin]+1) : memo[i-coin]+1; 
                }
            }
            // make sure to invalid the amount if no coins match
            if (memo[i]==0) memo[i]=-1;
        }

        return memo[amount];
    }
}
```
