#1300

Sum of Mutated Array Closest to Target

specialist · 935 · lc medium +32 · verified · 46.2% accepted · 1,204 likes · top 30%

Description

Choose an integer value and replace every element in arr that exceeds value with value itself. Find the value that makes the resulting array sum as close as possible to target (minimizing the absolute difference).

If two values produce equal differences, return the smaller one. The answer does not need to come from arr.

Example 1:

Input: arr = [4,9,3], target = 10
Output: 3
Explanation: When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer.

Example 2:

Input: arr = [2,3,5], target = 10
Output: 5

Example 3:

Input: arr = [60864,25176,27249,21296,20204], target = 56803
Output: 11361

Code

1
2
3