# Sum of Mutated Array Closest to Target in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

Suppose we have an integer array arr and a target value target, we have to find the integer value such that when we change all the integers larger than value in the given array will be equal to value, the sum of the array gets as nearest as possible to target. If they are same, then return the minimum such integer. So if the array is like [4,9,3] and target is 10, then the output will be 3 as using 3, the array will be [3,3,3], so the sum is 9, that is nearest element to 10.

To solve this, we will follow these steps −

• n := size of array, avg := total / n, set sum := 0 and cnt := 0
• for i in range 0 to n – 1
• if arr[i] <= avg, then sum := sum + arr[i], and increase cnt by 1
• if target – sum = 0, then return avg
• high := ceiling of (target - sum) / (n - cnt)
• low := floor of (target - sum) / (n - cnt)
• lowDiff := |target – (low*(n - cnt) + sum)|
• highDiff := |target – (high*(n - cnt) + sum)|
• if lowDiff <= highDiff, then return low
• return high.

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int findBestValue(vector<int>& arr, int target) {
int n = arr.size();
int avg = target / n;
int sum = 0;
int cnt = 0;
for(int i = 0; i < n; i++){
if(arr[i] <= avg){
sum += arr[i];
cnt++;
}
}
if(target - sum == 0)return avg;
int high = ceil(((target - sum) * 1.0)/ ((n - cnt) * 1.0));
int low = floor(((target - sum) * 1.0) / ((n - cnt) * 1.0));
int lowDiff = abs(target - (low * (n - cnt) + sum));
int highDiff = abs(target - (high * (n - cnt) + sum));
if( lowDiff <= highDiff)return low;
return high;
}
};
main(){
vector<int> v = {4,9,3,2};
Solution ob;
cout << (ob.findBestValue(v, 10));
}

## Input

[4,9,3,2]
10

## Output

3
Updated on 02-May-2020 12:39:23