Binary Search solution
class Solution:
def findBestValue(self, A: List[int], target: int) -> int:
""" tc O(Nlg(max(A))) sc O(1)
find a minimun integer x, so that sum_at_most(x) == target +-1?
x range [0,max(A)]?
"""
n = len(A)
def sum_at(x):
res = 0
for a in A:
if a > x:
res += x
else:
res += a
return res
l,r = 0,max(A)#10000#target//n, target+1
while l < r:
m = l + (r-l+1)//2
# find the max x so that sum of array is smaller than target
if sum_at(m) <= target:
l = m
else:
r = m-1
# check if (l+1) result a smaller absolute difference
sum1 = sum_at(l+1)
sum2 = sum_at(l)
if abs(sum1-target) >= abs(sum2-target):
return l # we need to find minimun x if l and l+1 both qualify
else:
return l+1