[LeetCode] Sum of Mutated Array Closest to Target

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
long search(vector<int>& arr, long& m) {
long res = 0;
for(auto& n : arr)
res += (n > m ? m : n);
return res;
}
public:
int findBestValue(vector<int>& arr, int target) {
long l = 0, r = *max_element(begin(arr), end(arr)), res = INT_MAX, diff = INT_MAX;
while(l <= r) {
long m = l + (r - l) / 2;
long s = search(arr, m);
if(abs(target - s) < diff) {
res = m;
diff = abs(target - s);
} else if(abs(target - s) == diff and res > m) {
res = m;
}

if(s >= target) r = m - 1;
else l = m + 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/09/PS/LeetCode/sum-of-mutated-array-closest-to-target/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.