You are assembling a character loadout for a game. There are several base gear sets, and you must equip exactly one of them. There are also several kinds of upgrade gem; for each kind you may attach it zero, one, or two times to the equipped gear set (never more than two of the same kind, and any subset of kinds may be skipped entirely). Given a target budget, choose one base gear set and a count of 0, 1, or 2 for each gem kind so that the total cost of the loadout is as close as possible to the target. If two different achievable totals are equally close to the target, report the smaller total.
n — the number of base gear sets (1 <= n <= 10).n integers — the cost of each base gear set (1 <= cost <= 10^4).m — the number of upgrade gem kinds (1 <= m <= 10).m integers — the cost of a single copy of each gem kind (1 <= cost <= 1000).target — the target budget (1 <= target <= 10^4).Print a single integer: the achievable total cost (one base gear set plus 0, 1, or 2 copies of each gem kind) that is closest to target. If two achievable totals are equally close to target, print the smaller one.
Example 1
Input
2 50 70 2 30 40 100
Expected
100
Explanation
Equip the 70-cost gear set and attach exactly one copy of the 30-cost gem (and zero copies of the 40-cost gem): total = 70 + 30 = 100, which exactly matches the target, so the answer is 100.
Example 2
Input
2 20 30 3 40 50 1000 180
Expected
170
Explanation
Equip the 30-cost gear set with one 40-cost gem and two 50-cost gems: total = 30 + 40 + 100 = 170, which is 10 away from the target of 180. No other combination of a base set with 0-2 copies of each gem kind gets closer (using the 1000-cost gem always overshoots by far more), so 170 is the answer.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →