題目如下:
Given an integer array
arrand a target valuetarget, return the integervaluesuch that when we change all the integers larger thanvaluein the given array to be equal tovalue, the sum of the array gets as close as possible (in absolute difference) totarget.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: 5Example 3:
Input: arr = [60864,25176,27249,21296,20204], target = 56803 Output: 11361Constraints:
1 <= arr.length <= 10^41 <= arr[i], target <= 10^5
解題思路:首先對arr進行排序。如果要把數組中所有大於value的數替換成value,那么可以通過二分查找的方法找出value在arr中出現的位置,左半部分的元素不需要改變,直接求和,右半部分的元素的和為 length * value。
代碼如下:
class Solution(object): def findBestValue(self, arr, target): """ :type arr: List[int] :type target: int :rtype: int """ import bisect diff = float('inf') res = 0 arr.sort() val = [] count = 0 for i in arr: count += i val.append(count) for v in range(0,arr[-1] + 1): inx = bisect.bisect_right(arr,v) amount = v * (len(arr) - inx) if inx > 0:amount += val[inx-1] if diff > abs(amount - target): diff = abs(amount - target) res = v return res
