leetcode 1300 - Sum of Mutated Array Closest to Target

https://leetcode.com/problems/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

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//O(NlogN + Max(arr)*logMax(arr))
class Solution {
public:
int findBestValue(vector<int>& arr, int target) {
sort(arr.begin(), arr.end());

int size = arr.size();
vector<long> sum(size);
sum[0] = arr[0];

for (int i = 1; i < size; i++) {
sum[i] = sum[i-1] + arr[i];
}

long min_diff = INT_MAX;
int ans;

for (long i = 0; i <= arr[size-1]; i++) {
auto it = upper_bound(arr.begin(), arr.end(), i);

int j = it - arr.begin();

long prefix_sum = j - 1 >= 0 ? sum[j-1] : 0;
long diff = abs(prefix_sum + (size - j) * i - target);

if (diff < min_diff) {
min_diff = diff;
ans = i;
}
}

return ans;
}
};

//O(NlogN + max(arr))
class Solution {
public:
int findBestValue(vector<int>& arr, int target) {
sort(arr.begin(), arr.end(), greater<int>());

int sum = 0;
for (int a : arr)
sum += a;

int i = 0;
int min_diff = INT_MAX;
int ans;

for (int num = arr[0]; num >= 0; num--) {
while (i < (int)arr.size() && arr[i] > num) {
sum -= arr[i];
i++;
}

int diff = abs(sum + num * i - target);
if (diff <= min_diff) {
min_diff = diff;
ans = num;
}
}

return ans;
}
};