Sum of Mutated Array Closest to Target

Given an integer array arr and a target value target, return the integer value such that when all integers larger than value in arr are changed to be equal to value, the sum of the array gets as close as possible, by absolute difference, to target.

In case of a tie, return the minimum such integer.

Notice that the answer is not necessarily a number from arr.

Example 1
Inputarr = [4,9,3], target = 10
Output3
When using 3, arr converts to [3, 3, 3], which sums to 9, and that is the optimal answer.
Example 2
Inputarr = [2,3,5], target = 10
Output5
Using value 5 leaves the array as [2, 3, 5], whose sum is 10, exactly matching the target.

Constraints

  • 1 <= arr.length <= 10^4
  • 1 <= arr[i], target <= 10^5

Asked at 2 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate