Array Manipulation and Sum
Last Updated :
16 Sep, 2022
Given an array arr[] of N integers and an integer S. The task is to find an element K in the array such that if all the elements from the array > K are made equal to K then the sum of all the elements of the resultant array becomes equal to S. If it is not possible to find such an element then print -1 .
Examples:
Input: M = 15, arr[] = {12, 3, 6, 7, 8}
Output: 3
Resultant array = {3, 3, 3, 3, 3}
Sum of the array elements = 15 = S
Input: M = 5, arr[] = {1, 3, 2, 5, 8}
Output: 1
Approach: Sort the array. Traverse the array considering that the value of K is equal to the current element and then check if sum of the previous elements + (K * number of remaining elements) = S. If yes then print the value of K, if no such element found then print -1 in the end.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int getElement( int a[], int n, int S)
{
sort(a, a + n);
int sum = 0;
for ( int i = 0; i < n; i++) {
if (sum + (a[i] * (n - i)) == S)
return a[i];
sum += a[i];
}
return -1;
}
int main()
{
int S = 5;
int a[] = { 1, 3, 2, 5, 8 };
int n = sizeof (a) / sizeof (a[0]);
cout << getElement(a, n, S);
return 0;
}
|
Java
import java.util.Arrays;
class GFG
{
static int getElement( int a[], int n, int S)
{
Arrays.sort(a);
int sum = 0 ;
for ( int i = 0 ; i < n; i++)
{
if (sum + (a[i] * (n - i)) == S)
return a[i];
sum += a[i];
}
return - 1 ;
}
public static void main(String[] args)
{
int S = 5 ;
int a[] = { 1 , 3 , 2 , 5 , 8 };
int n = a.length;
System.out.println(getElement(a, n, S));
}
}
|
Python 3
def getElement(a, n, S) :
a.sort();
sum = 0 ;
for i in range (n) :
if ( sum + (a[i] * (n - i)) = = S) :
return a[i];
sum + = a[i];
return - 1 ;
if __name__ = = "__main__" :
S = 5 ;
a = [ 1 , 3 , 2 , 5 , 8 ];
n = len (a) ;
print (getElement(a, n, S)) ;
|
C#
using System;
class GFG
{
static int getElement( int [] a, int n, int S)
{
Array.Sort(a);
int sum = 0;
for ( int i = 0; i < n; i++)
{
if (sum + (a[i] * (n - i)) == S)
return a[i];
sum += a[i];
}
return -1;
}
public static void Main()
{
int S = 5;
int [] a = { 1, 3, 2, 5, 8 };
int n = a.Length;
Console.WriteLine(getElement(a, n, S));
}
}
|
PHP
<?php
function getElement( $a , $n , $S )
{
sort( $a , 0);
$sum = 0;
for ( $i = 0; $i < $n ; $i ++)
{
if ( $sum + ( $a [ $i ] *
( $n - $i )) == $S )
return $a [ $i ];
$sum += $a [ $i ];
}
return -1;
}
$S = 5;
$a = array (1, 3, 2, 5, 8);
$n = sizeof( $a );
echo getElement( $a , $n , $S );
?>
|
Javascript
<script>
function getElement(a, n, S)
{
a.sort();
var sum = 0;
for ( var i = 0; i < n; i++) {
if (sum + (a[i] * (n - i)) == S)
return a[i];
sum += a[i];
}
return -1;
}
var S = 5;
var a = [ 1, 3, 2, 5, 8 ];
var n = a.length;
document.write(getElement(a, n, S));
</script>
|
Complexity Analysis:
- Time Complexity: O(N*logN)
- Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...