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
Sum of Mutated Array Closest to TargetInput Array:493Target: 10Mutation Process:value = 0 → [0,0,0] → sum = 0value = 2 → [2,2,2] → sum = 6value = 3 → [3,3,3] → sum = 9 ✓value = 5 → [4,5,3] → sum = 12When value = 3:49→33=3+3+3=9Result Analysis:|9 - 10| = 1 ← closest differencevalue = 4: sum = 11, |11-10| = 1Tie: both diff = 1, choose min valueAnswer: 3Efficient: Use binary search to find optimal mutation value
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
Asked in
Google 25 Amazon 18 Facebook 12 Microsoft 10
28.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen