forked from Mohammed-Shoaib/Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC1300.cpp
More file actions
executable file
·34 lines (29 loc) · 715 Bytes
/
LC1300.cpp
File metadata and controls
executable file
·34 lines (29 loc) · 715 Bytes
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
/*
Problem Statement: https://leetcode.com/problems/sum-of-mutated-array-closest-to-target/
*/
class Solution {
public:
int findBestValue(vector<int>& arr, int target) {
int low, mid, high, sum;
low = 1;
high = *max_element(arr.begin(), arr.end()) + 1;
// binary search
while (low < high) {
mid = low + (high - low) / 2;
sum = get_sum(mid, arr);
if (target <= sum)
high = mid;
else
low = mid + 1;
}
if (abs(target - get_sum(low - 1, arr)) <= abs(target - get_sum(low, arr)))
low--;
return low;
}
int get_sum(int x, vector<int> arr) {
for (int i = 0; i < arr.size(); i++)
if (arr[i] > x)
arr[i] = x;
return accumulate(arr.begin(), arr.end(), 0);
}
};