THINK FIRST·CODE LATER

← All labs

Minimum number of coins

Problem

Given k coin denominations (unlimited supply of each) and an amount, find the minimum number of coins whose values add up exactly to the amount, or report that it is impossible. Greedy "largest coin first" is not correct in general (coins {1, 3, 4}, amount 6), so use bottom-up dynamic programming: dp[x] = fewest coins for amount x.

Input. The first line holds k (1 ≤ k ≤ 50). The second line holds the k distinct positive coin values (each ≤ 10 000). The third line holds the amount (0 ≤ amount ≤ 100 000).

Output. One line:

Minimum coins: X

where X is the minimum count, 0 for amount 0, or -1 if the amount cannot be made.

Example.

Input:

3
1 3 4
6

Output:

Minimum coins: 2

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d8-1-data-1.txt

3
1 3 4
6
What your program must print for d8-1-data-1.txt
Minimum coins: 2

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d8-1-data-1.txt

Windows PowerShell does not understand <:

Get-Content d8-1-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.