Cash Machine
InterviewTime limit1sMemory limit128 MB
Given a cash target and limited counts of several bill denominations, find the maximum total not exceeding the target using a bounded-knapsack style search.
- Level
Medium4 of 10
- Topics
- Dynamic programming, Brute force
- Solved
- No attempts yet
Problem
A bank plans to install a cash-withdrawal machine. For a requested amount, the machine delivers bills from its supply. It uses exactly distinct denominations , and for each denomination it holds a supply of bills.
For example, with , , means the machine holds 10 bills of denomination 100, 4 bills of denomination 50, and 5 bills of denomination 10.
Let be the requested amount. Write a program that computes the maximum amount not exceeding that the machine can deliver using its available bills.
Input
The input contains several data sets and is read until end-of-file. Each data set describes one transaction in the form
cash N n1 D1 n2 D2 ... nN DN
where is the requested amount, is the number of denominations, is the number of available bills of denomination , and for . Whitespace may appear freely between the numbers. The input is always well-formed.
Output
For each data set, print on its own line the maximum amount of cash, not exceeding the requested amount, that the machine can deliver.
Notes
If the requested amount cannot be formed exactly, deliver the largest amount that does not exceed it. If the machine has no bills to offer (for example ) or the requested amount is , the delivered amount is . Several different bill combinations may add up to the same delivered amount.