The Riddle
Time limit1sMemory limit128 MB
Find the minimum prefix length of a coin sequence so that all values from 1 to K are achievable as subset sums, using the classic greedy reachable-range extension, or report -1.
- Level
Medium4 of 10
- Topics
- Greedy, Array, Prefix sum
- Solved
- No attempts yet
Problem
Eleonora's grandmother Sercha loves posing math riddles to her grandchildren. On the family's last trip she gave this one:
"Suppose a shop sells items priced from to . I have coins whose denominations, in order, are . I am old and want to carry as few coins as possible. If I pick the coins up one by one starting from , how many coins from the front must I take so that, using subsets of the coins I have taken, I can pay every price from to exactly?"
Eleonora answered within seconds and thought, "Basic algorithms like this are easy now!"
Help Eleonora. Taking the coins from the front in the given order, find the smallest number of coins that must be taken so that every amount from to can be formed as a subset sum of the taken coins. If this is impossible even after taking all coins, output .
Input
The first line contains the number of test cases .
For each test case, the first line contains two integers and (, ). The second line contains the coin denominations in order, separated by spaces ().
Output
For each test case, print on its own line the minimum number of coins that must be taken from the front so that every price from to can be paid as a subset sum of the taken coins. If it is impossible even after taking all coins, print .