Problem statement

https://binarysearch.com/problems/Update-List-Sum-Closest-to-Target/

Solution

Equal to Leetcode 1300. Sum of Mutated Array Closest to Target

Complexity

It is O(n log M) for time and O(n) for space.

Code

class Solution:
    def solve(self, arr, t):
        def check(v):
            return sum(min(a, v) for a in arr)

        beg, end = 0, max(arr)
        while beg + 1 < end:
            mid = (beg + end) // 2
            if check(mid) <= t:
                beg = mid
            else:
                end = mid
                
        return beg + (2*t > check(beg) + check(beg + 1))