Array Manipulation and Sum using C/C++

CC++Server Side ProgrammingProgramming

Here we will see one problem, suppose one array is given. There are n elements. Another value S is also given. We have to find an element K in the array, such that, if all elements which are greater than K, are made equal to K, then the sum of all elements of the final array becomes equal to S. If that is not possible, then return -1.

Suppose the elements are {12, 6, 3, 7, 8}, and sum value is 15, the output is 3. The final array is {3, 3, 3, 3, 3}, Sum of array elements is S = 15

Algorithm

getVal(arr, n, S) 

Begin
   sort arr as increasing order
   sum := 0
   for i in range 0 to n-1, do
      if sum + (arr[i] * (n - i)) is same as S, then
         return arr[i]
      end if
      sum := sum + arr[i]
   done
   return -1
End

Example

#include <iostream>
#include <algorithm>
using namespace std;
int getVal(int arr[], int n, int S) {
   sort(arr, arr + n);
   int sum = 0;
   for (int i = 0; i < n; i++) {
      if (sum + (arr[i] * (n - i)) == S) //if current value is satisfying, then return arr[i]
         return arr[i];
      sum += arr[i];
   }
   return -1;
}
int main() {
   int S = 15;
   int arr[] = { 12, 3, 6, 7, 8 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << getVal(arr, n, S);
}

Output

3
raja
Published on 20-Aug-2019 07:45:13
Advertisements