Medium
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 <= 104
1 <= arr[i], target <= 105
import java.util.Arrays;
public class Solution {
public int findBestValue(int[] arr, int target) {
Arrays.sort(arr);
int n = arr.length;
int lo = 0;
int hi = arr[n - 1];
int min = Integer.MAX_VALUE;
int ans = -1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
int m = check(mid, arr, target);
int l = check(mid - 1, arr, target);
int r = check(mid + 1, arr, target);
if (m < min || (m == min && ans > mid)) {
min = m;
ans = mid;
} else if (l <= r) {
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
public int check(int v, int[] arr, int target) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] >= v) {
return Math.abs(sum + (arr.length - i) * v - target);
} else {
sum += arr[i];
}
}
return Math.abs(sum - target);
}
}