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
struct Solution;
impl Solution {
fn find_best_value(mut arr: Vec<i32>, mut target: i32) -> i32 {
arr.sort_unstable();
let n = arr.len();
let mut i = 0;
while i < n && target > arr[i] * (n - i) as i32 {
target -= arr[i];
i += 1;
}
if i == n {
return arr[n - 1];
}
let res = target / (n - i) as i32;
if (res + 1) * (n - i) as i32 - target < target - res * (n - i) as i32 {
res + 1
} else {
res
}
}
}
#[test]
fn test() {
let arr = vec![4, 9, 3];
let target = 10;
let res = 3;
assert_eq!(Solution::find_best_value(arr, target), res);
let arr = vec![2, 3, 5];
let target = 10;
let res = 5;
assert_eq!(Solution::find_best_value(arr, target), res);
let arr = vec![60864, 25176, 27249, 21296, 20204];
let target = 56803;
let res = 11361;
assert_eq!(Solution::find_best_value(arr, target), res);
}