Loading...
Loading...
Your class is buying three different gifts for a teacher from an online store. The class has collected B rupees. You want the total of the three gifts to be as close to B as possible, either below or above. Print that total. If two totals are equally close, one below B and one above, print the smaller total.
Example 1
Input
4 100 20 45 30 60
Output
95
The totals are 95, 110, 125 and 135. 95 is only 5 away from 100.
Example 2
Input
4 12 1 3 5 7
Output
11
The totals are 9, 11, 13 and 15. 11 and 13 are both 1 away, so the smaller one, 11, wins.
Try the problem first. Open one hint at a time.
Sort the prices, then fix the cheapest gift of the three with a loop.
For the other two, put one index just after it and one at the end. If the total is below B, move the left index right. If it is above B, move the right index left.
After every total, compare its distance to B with the best one so far. On an equal distance, keep the smaller total.
If a total equals B, nothing can be closer, so you can stop. Keep prices, B and totals in long.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor