Problem:
Coin Changing Problem

Find the minimum number of coins to make change for n cents using coins of denominations d1, d2,.., dm. The coins can be used any number of times.

Input

n m
d1 d2 ... dm

Two integers n and m are given in the first line. The available denominations are given in the second line.

Output

Print the minimum number of coins in a line.

Constraints

1 ≤ n ≤ 50000

1 ≤ m ≤ 20

1 ≤ denomination ≤ 10000

The denominations are all different and contain 1.

Sample Input 1

55 4
1 5 10 50

Sample Output 1

2

Sample Input 2

15 6
1 2 7 8 12 50

Sample Output 2

2

Sample Input 3

65 6
1 2 7 8 12 50

Sample Output 3

3

Solution in JAVA (judge verdict: Accepted)


import java.util.Scanner;

public class Main {

    public static int coinChange(int[] coins, int amount) {
        if (coins == null || coins.length == 0) {
            return 0;
        }
        int[] dp = new int[amount + 1];

        for (int i = 1; i < dp.length; i++) {
            dp[i] = -1;
        }

        for (int coinsNum = 1; coinsNum <= coins.length; coinsNum++) {
            for (int amountN = 1; amountN <= amount; amountN++) {
                if ((amountN - coins[coinsNum - 1] >= 0) && dp[amountN - coins[coinsNum - 1]] != -1) {
                    int prevTotal = dp[amountN - coins[coinsNum - 1]];
                    if (dp[amountN] == -1) {
                        dp[amountN] = prevTotal + 1;
                    } else {
                        dp[amountN] = Math.min(dp[amountN], prevTotal + 1);
                    }
                }
            }
        }
        return dp[amount];
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int amount = scanner.nextInt();
        int n = scanner.nextInt();
        int[] coins = new int[n];
        for (int i = 0; i < n; i++) {
            coins[i] = scanner.nextInt();
        }
        System.out.println(coinChange(coins, amount));
    }
}