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 Target INPUT Array: arr 4 idx 0 9 idx 1 3 idx 2 target = 10 Current sum: 4+9+3 = 16 Sum exceeds target by 6 Search Range value: 0 to max(arr) = 9 Find best mutation value arr=[4,9,3] target=10 ALGORITHM STEPS 1 Binary Search Setup lo=0, hi=max(arr)=9 2 Try mid values mid=4: sum=4+4+3=11 mid=3: sum=3+3+3=9 3 Compare distances |11-10|=1, |9-10|=1 Both have diff=1 4 Tie-breaker rule Return minimum value min(3, 4) = 3 Value Sum Diff 3 9 1 (OK) 4 11 1 FINAL RESULT Mutated Array (value=3): 3 4-->3 3 9-->3 3 unchanged New Sum: 3+3+3 = 9 |9 - 10| = 1 Output 3 OK - Minimum value with closest sum to target return 3 Key Insight: Binary search finds the optimal mutation value in O(n log m) time where m = max(arr). For each candidate value, compute sum by capping elements greater than value. The sum function is monotonic: larger values give larger sums, enabling binary search for closest sum. TutorialsPoint - Sum of Mutated Array Closest to Target | Optimal Binary Search Approach
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