topic
Give you an integer array arr and a target value target. Please return an integer value so that after all the values in the array greater than value become value, the sum of the array is closest to the target (closest to the absolute value of the difference between the two) Minimum).
If there are multiple schemes that make the sum closest to the target, please return the smallest value among these integers.
Note that the answer is not necessarily the number in arr. link
Ideas
At first I wanted to use the average, but not all elements in the array need to be changed value
. .
Determining the value of the range [0,max(arr)]
is set threshold
, it is determined that the array elements than threshold
the elements becomes threshold
the value closest to the array and target
may find out by strictly greater than half of target
the first one threshold
, in comparison threshold
with threshold-1
the array and, i.e. The result can be determined.
class Solution {
public int findBestValue(int[] arr, int target) {
int left=0,right=0;
for(int x:arr){
right=Math.max(right,x);
}
while(left<right){
int mid=left+(right-left)/2;
if(calSum(arr,mid)<target){
left=mid+1;
}else{
right=mid;
}
}
/*
这里left为第一个使数组和大于target的threshold
则left-1必然使得数组和小于target,即判断这两个哪个接近target
*/
if(target-calSum(arr,left-1)<=calSum(arr,left)-target){
return left-1;
}
return left;
}
int calSum(int[]arr,int threshold){
int sum=0;
for(int x:arr){
sum+=Math.min(threshold,x);
}
return sum;
}
}