Skip to content

Commit 7a3ac25

Browse files
Create sum_of_mutated_array_closest_to_target.cpp
1 parent cac1a60 commit 7a3ac25

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
public:
3+
int findBestValue(vector<int>& arr, int target) {
4+
5+
/*
6+
The only catch in the problem is we cannot change elements that are previously visited. Only current and all elements from current to end can be mutated.
7+
*/
8+
9+
int n = arr.size();
10+
sort(arr.begin(), arr.end());
11+
12+
int trailingSum = 0, sumNeeded;
13+
for(int i=0; i<n; i++) {
14+
sumNeeded = int(round((target - trailingSum - 0.00001) / (n - i)));
15+
if(sumNeeded <= arr[i]) {
16+
return sumNeeded;
17+
}
18+
trailingSum += arr[i];
19+
}
20+
return arr[arr.size() - 1];
21+
22+
}
23+
};

0 commit comments

Comments
 (0)