Medium
分析题目
很显然,这种情况,我们可以使用二分法来进行求解。
尝试写一下代码
AC!
python3
class Solution:
def sumList(self, value ,arr):
sum = 0
for i in arr:
if i >= value:
sum += value
else:
sum += i
return sum
def findBestValue(self, arr: List[int], target: int) -> int:
left = 0
m = max(arr)
right = m
while left < right:
mid = (left + right) // 2
if self.sumList(mid,arr) > target:
right = mid
else:
left = mid + 1
s = self.sumList(left, arr)
if s == target:
return left
elif s < target:
other_s = self.sumList(left+1, arr)
if abs(s-target) > abs(other_s-target) and left+1 <= m:
return left + 1
else:
other_s = self.sumList(left-1, arr)
if abs(s-target) >= abs(other_s-target) and left-1 >= 0:
return left - 1
return left