Sum of Mutated Array Closest to Target — LeetCode 1300 Python Solution

MediumArrayBinary SearchSorting
Problem
#1300
Reading time
2 min

The 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.

Example

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.

Python solution

Python
class Solution:
    def findBestValue(self, arr: List[int], target: int) -> int:
        arr.sort()
        s = list(accumulate(arr, initial=0))
        ans, diff = 0, inf
        for value in range(max(arr) + 1):
            i = bisect_right(arr, value)
            d = abs(s[i] + (len(arr) - i) * value - target)
            if diff > d:
                diff = d
                ans = value
        return ans

Complexity

MeasureComplexity
TimeO(log n) or O(n log n)
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 1300. Sum of Mutated Array Closest to Target is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1300. Sum of Mutated Array Closest to Target?
LeetCode 1300. Sum of Mutated Array Closest to Target is rated Medium on LeetCode.
What topics does LeetCode 1300. Sum of Mutated Array Closest to Target cover?
LeetCode 1300. Sum of Mutated Array Closest to Target is tagged Array, Binary Search and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview