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^4
1 <= arr[i], target <= 10^5
class Solution:
    def findBestValue(self, arr: List[int], target: int) -> int:
        vals = sorted(arr)
        l = len(vals)
            
        diff = float('inf')
        num = -1
        m = vals[-1]
        i = 0
        prev_sum = 0 
        for n in range(m+1):
            if n > target:
                break
            
            while n > vals[i]:
                prev_sum += vals[i]
                i += 1
                    
            total = (n * (l-i)) + prev_sum
            new_diff = abs(target - total)
            if new_diff < diff:
                diff = new_diff
                num = n
                
        
        return num
                
            
            

class Solution:
    def findBestValue(self, arr: List[int], target: int) -> int:
        vals = sorted(arr)
        l = len(vals)
            
        diff = float('inf')
        num = -1
        m = vals[-1]
        i = 0
        prev_sum = 0 
        for n in range(m+1):
            if n > target:
                break
            
            while n > vals[i]:
                prev_sum += vals[i]
                i += 1
                    
            total = (n * (l-i)) + prev_sum
            new_diff = abs(target - total)
            if new_diff < diff:
                diff = new_diff
                num = n
                
        
        return num
                
            
            
