Sum of Mutated Array Closest to Target Problem
Description
LeetCode Problem 1300.
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 neccesarilly a number 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
Constraints:
1 <= arr.length <= 10^41 <= arr[i], target <= 10^5
Solution
Approach: Sort and Spread the Remaining Target
Let S(v) be the array sum after capping every element at v. It grows as v grows, so we look for the v where S(v) crosses target.
Sort the array and walk through it, keeping rest, the part of target that the elements from index i on still have to contribute (start with rest = target). Let cnt = n - i be the number of these elements.
- If
arr[i] * cnt >= rest, capping all ofarr[i..]at a common valuev <= arr[i]is enough, while the smaller elements beforeistay unchanged. ThenS(v) = (sum before i) + cnt * v, so we wantcnt * vas close torestas possible. The best integer isv = rest / cnt(rounded down) orv + 1. Withr = rest % cnt, the distances arerandcnt - r; pickvwhenr <= cnt - r, which also breaks a tie towards the smaller value, as the problem asks. - Otherwise even keeping
arr[i]whole is not enough: subtract it fromrestand move on.
We never pick a v below the previous element: at the earlier step we had arr[i - 1] * (cnt + 1) < rest + arr[i - 1], so rest / cnt > arr[i - 1]. If the loop ends without returning, the whole array sums to less than target, every v >= max(arr) gives that same sum, and the smallest of them is max(arr).
Note that the answer may be 0: for arr = [5, 5] and target = 1, both v = 0 and v = 1 miss by 1, and the tie goes to 0.
Complexity: O(n log n) time for the sort and O(n) space for the sorted copy.
class Solution:
def findBestValue(self, arr: List[int], target: int) -> int:
arr = sorted(arr)
n = len(arr)
rest = target # what the elements from index i on still have to add up to
for i, x in enumerate(arr):
cnt = n - i
if x * cnt >= rest:
# The answer caps arr[i:] at a value v <= x; arr[:i] stay as they are.
# cnt * v should be close to rest: try v = rest // cnt and v + 1.
v, r = divmod(rest, cnt)
return v if r <= cnt - r else v + 1
rest -= x
return arr[-1] # even without capping the sum is at most target