Home  >  Article  >  Backend Development  >  Array operations and sums using C/C++

Array operations and sums using C/C++

PHPz
PHPzforward
2023-09-02 22:29:061330browse

Array operations and sums using C/C++

Here we will see a problem, assuming an array is given. There are n elements. Another value S is also given. We must find an element K in the array such that if all elements greater than K are equal to K, then the sum of all elements of the final array equals S. If not possible, then -1 is returned.

Assume the elements are {12, 6, 3, 7, 8} and the sum value is 15, then the output is 3. The final array is {3, 3, 3, 3, 3}, and the sum of the 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

The above is the detailed content of Array operations and sums using C/C++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete
Previous article:C program for radix sortNext article:C program for radix sort