Problem Description
Given an integer array arr and a target, find an integer value such that when every element in arr greater than value is replaced with value, the sum of the array is as close as possible (in absolute difference) to target. In the event of a tie, return the smallest such value. Note that the returned value is not necessarily an element of arr.
Key Insights
- Sorting the array simplifies computation by grouping values and enabling efficient prefix sum calculations.
- A binary search can be employed over the range of possible values (from 0 to the maximum element in arr) to determine the optimal mutation value.
- Precomputed prefix sums allow quick determination of the mutated sum for each candidate value.
- Care must be taken to handle tie cases by preferring the smaller candidate.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting and binary search evaluation. Space Complexity: O(n) for storing prefix sums.
Solution
The solution first sorts the input array and calculates prefix sums to enable fast sum queries. Then, it uses binary search between 0 and the maximum element in the array to find the candidate value that, when used to cap the array’s values, minimizes the absolute difference between the mutated sum and the target. For any given candidate value, the prefix sum array quickly computes the sum of all elements less than or equal to the candidate, and the remainder of the sum is computed by multiplying the candidate by the count of larger elements. The candidate with the smallest difference is returned, resolving ties by choosing the smaller candidate.