Sum of Mutated Array Closest to Target — LeetCode 1300 Python Solution
- Problem
- #1300
- Pattern
- Monotonic Stack
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(log n) or O(n log n) |
| Space | O(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.