Sum of Mutated Array Closest to Target - Problem
Imagine you have an array of numbers and you need to cap some values to reach a specific target sum. Given an integer array arr and a target value, you need to find the optimal threshold value such that:
- All numbers greater than the threshold get replaced with the threshold itself
- All numbers less than or equal to the threshold remain unchanged
- The resulting array sum is as close as possible to the target
Your goal is to return this optimal threshold value. In case of a tie (two thresholds give equally close sums), return the smaller threshold.
Important: The answer doesn't have to be a number from the original array - it can be any integer!
Example: For array [4,9,3] and target 10, if we use threshold 3, we get [3,3,3] โ sum = 9. If we use threshold 4, we get [4,4,3] โ sum = 11. Since |10-9| = 1 and |10-11| = 1, both are equally close, so we return the smaller threshold: 3.
Input & Output
example_1.py โ Basic Case
$
Input:
arr = [4,9,3], target = 10
โบ
Output:
3
๐ก Note:
When threshold = 3: [4,9,3] becomes [3,3,3] with sum = 9. When threshold = 4: [4,9,3] becomes [4,4,3] with sum = 11. Both have distance 1 from target 10, but we return the smaller threshold: 3.
example_2.py โ Exact Match
$
Input:
arr = [2,3,5], target = 10
โบ
Output:
5
๐ก Note:
When threshold = 5: [2,3,5] remains [2,3,5] with sum = 10. This exactly matches our target, so distance = 0. Answer is 5.
example_3.py โ Large Threshold Needed
$
Input:
arr = [60864,25176,27249,21296,64451,35842,15611,24533,18808,44838], target = 56803
โบ
Output:
11361
๐ก Note:
This requires testing various thresholds to find the one that produces a sum closest to 56803. The optimal threshold turns out to be 11361.
Constraints
- 1 โค arr.length โค 104
- 1 โค arr[i], target โค 105
- The answer is guaranteed to be unique
Visualization
Tap to expand
Understanding the Visualization
1
Original Requests
Employees request salaries: [4000, 9000, 3000]
2
Set Cap
CEO sets salary cap at 3000 (threshold = 3)
3
Apply Cap
Final salaries: [3000, 3000, 3000] = 9000 total
4
Check Target
Target budget was 10000, difference = 1000
5
Compare Options
Cap of 4000 gives total 11000 (diff=1000), same distance but higher cap, so prefer 3000
Key Takeaway
๐ฏ Key Insight: The monotonic relationship between threshold and sum allows us to use binary search, reducing time complexity from O(n ร max_value) to O(n log max_value).
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code