Sum of Mutated Array Closest to Target - Problem
Given an integer array arr and a target value target, return the integer value such that when we change all the integers larger than value in the given array to be equal to value, the sum of the array gets as close as possible (in 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.
Input & Output
Example 1 — Basic Case
$
Input:
arr = [4,9,3], target = 10
›
Output:
3
💡 Note:
When value = 3: [min(4,3), min(9,3), min(3,3)] = [3,3,3], sum = 9. When value = 4: sum = 11. Both |9-10|=1 and |11-10|=1, so return minimum value = 3.
Example 2 — Exact Target
$
Input:
arr = [2,3,5], target = 10
›
Output:
5
💡 Note:
When value = 5: no elements change since all ≤ 5, sum = 2+3+5 = 10 = target exactly.
Example 3 — Small Target
$
Input:
arr = [60864,25176,27249,21296,64451,35928,53067,25101,77699], target = 4
›
Output:
0
💡 Note:
Target is very small, so optimal value is 0 (makes all elements 0), giving sum closest to 4.
Constraints
- 1 ≤ arr.length ≤ 104
- 1 ≤ arr[i], target ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [4,9,3] and target 10
2
Process
Test different mutation values to find closest sum
3
Output
Return value 3 that gives sum closest to target
Key Takeaway
🎯 Key Insight: The sum is monotonic in the mutation value - binary search can efficiently find the optimal point
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code