A science center sells single-day exhibit tickets, each with its own price. A family visiting today has decided they will buy exactly two tickets — for the two exhibits they most want to see — no more and no less, but only if they can still afford to do so. If even the two cheapest tickets together cost more than they brought, they buy nothing at all and keep every unit of their money.
Given the list of available ticket prices and the amount of money the family brought, choose two distinct tickets to buy so as to leave as much money as possible afterward, and report that leftover amount (or the original budget, unchanged, if no affordable pair of two distinct tickets exists).
Line 1: two integers n and budget — the number of tickets available and the money on hand.
Line 2: n space-separated integers, the prices of the tickets.
A single integer: the maximum leftover money after buying exactly two distinct tickets, or budget unchanged if no two distinct tickets can be afforded together.
Example 1
Input
4 9 5 3 8 4
Expected
2
Explanation
Prices are [5,3,8,4], budget is 9. The two cheapest tickets are 3 and 4, costing 7 together, which fits within the 9-unit budget. Buying them leaves 9 - 7 = 2.
Example 2
Input
2 15 10 20
Expected
15
Explanation
Prices are [10,20], budget is 15. The only possible pair costs 10 + 20 = 30, which exceeds the 15-unit budget, so the family buys nothing and keeps all 15.
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 →