Farmer John is at the market to buy supplies for his farm. He carries K coins (1≤K≤16) in his pocket, and each coin has an integer value between 1 and 108. John plans to make N purchases (1≤N≤105) in a fixed order, and purchase i costs ci (1≤ci≤104).
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 N purchases in order. Print −1 if he cannot make all of his purchases.
In the example John has three coins worth 12, 15, and 10, and he must make purchases of 6, 3, 3, 2, 3, and 7 in that order. He pays for the first two purchases with the 10 coin (6+3=9≤10) and for the remaining four with the 15 coin (3+2+3+7=15). The 12 coin stays in his pocket.