No Change
Time limit1sMemory limit128 MB
Pay the ordered purchases with distinct coins, each covering one consecutive group within its value, to maximize unused value, or print -1.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Bit manipulation, Prefix sum, Binary search
- Solved
- No attempts yet
Problem
Farmer John is at the market to buy supplies for his farm. He carries coins () in his pocket, and each coin has an integer value between and . John plans to make purchases () in a fixed order, and purchase costs ().
While he works through that sequence, John may stop at any point and pay. To pay he hands over a single coin, and that coin settles every purchase he made since his previous payment, so it has to be worth at least the total of those purchases. The vendors have no change at all, so when John hands over a coin worth more than he owes, the difference is gone.
A coin leaves his pocket for good once he uses it, so the money John is left with is the total value of the coins he never used. Compute the largest amount of money John can be left with after making all purchases in order. Print if he cannot make all of his purchases.
Input
- Line 1: two integers and .
- Lines 2 through : each line contains the value of one of John's coins.
- Lines through : these lines contain the costs of John's intended purchases, in order.
Output
- Line 1: print the largest amount of money John can be left with, or if he cannot make all of his purchases.
Hint
In the example John has three coins worth , , and , and he must make purchases of , , , , , and in that order. He pays for the first two purchases with the coin () and for the remaining four with the coin (). The coin stays in his pocket.