
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sum of Mutated Array Closest to Target in C++
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
#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
Advertisements