Problem 875
Sum of Mutated Array Closest to Target
Medium · 20 pts · Array, Binary Search, Sorting
Problem
Choose a non-negative integer V and replace every array element larger than V by V. Make the sum of the changed array as close as possible to TARGET (smallest absolute difference), and print V; if two values of V tie, print the smaller one. The sum only grows with V, so binary search for the first V whose sum reaches TARGET and compare it with V - 1. V never needs to exceed the largest element.
Input
The first line contains N and TARGET. The second line contains the N integers.
Output
Print the best value V.
Constraints
1 <= N <= 10000; 1 <= A[i], TARGET <= 100000
Example input
3 10 4 9 3
Example output
3
Explanation
For 4 9 3 with TARGET = 10, V = 3 gives 3 + 3 + 3 = 9 and V = 4 gives 4 + 4 + 3 = 11, both 1 away. The smaller V wins, so the answer is 3.