1300. Sum of Mutated Array Closest to Target
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
题目:给你一个整数数组 arr
和一个目标值 target
,请你返回一个整数 value
,使得将数组中所有大于 value
的值变成 value
后,数组的和最接近 target
(最接近表示两者之差的绝对值最小)。如果有多种使得和最接近 target
的方案,请你返回这些整数中的最小值。请注意,答案不一定是 arr
中的数字。
思路:参考lee215。因为需要找到一个pivot
值,将大于等于pivot
的值替换为pivot
后,使得整个数组的和最接近target
。因此首先对数组进行排序,在位置i
时,如果arr[i] * (n-i)
的值大于target
,说明仍可以增大pivot
的值,更新pivot
的位置,在右移的过程中同时更新target
的值。
class Solution {
public:
int findBestValue(vector<int>& arr, int target) {
sort(arr.begin(), arr.end());
int n = arr.size(), i = 0;
while(i < n && target > arr[i] * (n-i))
target -= arr[i++];
// 减0.0001是为了在出现多种解时,取结果小的,如arr=[4, 9, 3], target=10
return i == n ? arr[n-1] : round((target-0.0001) / (n-i));
}
};