Minimum numbers to be appended such that mean of Array is equal to 1
Given an array arr[ ] of size N, the task is find minimum number of operation required to make mean of Array arr[ ] equal to 1. In one operation, a non-negative number can be appended in the end of the array.
Examples:
Input: N = 3, arr = {1, 1, 1}
Output: 0
Explanation:
As it can be seen that mean of arr[ ], (1+1+1)/3 = 1,
Therefore 0 operations required to make array good.
Input: N = 4, arr = {8, 4, 6, 2}
Output: 16
Explanation:
As the sum of the given array is 20 and number of element are 4.
Therefore we need to append 16 zero in the last of array, to make its mean equal to 1.
Approach: The above problem can be solved with the help of array sum and count of elements in array, i.e. N, as per below cases:
- If the array sum is less than N, the difference between them can be appended in the Array, and hence 1 operation is required.
- If the array sum is equal to N, then the mean will be equal to 1, and hence 0 operations are required.
- If the array sum is greater than N, then 0 can be appended in the array (arraySum – N) times. Hence (arraySum – N) operations are required.
Follow the steps below to solve the problem:
Below is the implementation of the above approach.
C++
#include<bits/stdc++.h>
using namespace std;
void minumumOperation( int N, int arr[]){
int sum_arr = 0;
sum_arr = accumulate(arr, arr+N, sum_arr);
if (sum_arr >= N)
cout<<sum_arr-N<<endl;
else
cout<<1<<endl;
}
int main(){
int N = 4;
int arr[] = {8, 4, 6, 2};
minumumOperation(N, arr);
}
|
Java
import java.io.*;
class GFG
{
static void minumumOperation( int N, int arr[])
{
int sum_arr = 0 ;
for ( int i = 0 ; i < N; i++)
{
sum_arr += arr[i];
}
if (sum_arr >= N)
System.out.println(sum_arr - N);
else
System.out.println( "1" );
}
public static void main(String[] args)
{
int N = 4 ;
int arr[] = { 8 , 4 , 6 , 2 };
minumumOperation(N, arr);
}
}
|
Python3
def minumumOperation(N, arr):
sum_arr = sum (arr)
if sum_arr > = N:
print (sum_arr - N)
else :
print ( 1 )
N = 4
arr = [ 8 , 4 , 6 , 2 ]
minumumOperation(N, arr)
|
C#
using System;
class GFG
{
static void minumumOperation( int N, int []arr){
int sum_arr = 0;
for ( int i = 0; i < N; i++) {
sum_arr = sum_arr + arr[i];
}
if (sum_arr >= N)
Console.Write(sum_arr-N);
else
Console.Write(1);
}
static public void Main (){
int N = 4;
int []arr = {8, 4, 6, 2};
minumumOperation(N, arr);
}
}
|
Javascript
<script>
function minumumOperation(N, arr) {
let sum_arr = 0;
for (let i = 0; i < N; i++) {
sum_arr = sum_arr + arr[i];
}
if (sum_arr >= N)
document.write(sum_arr - N + "<br>" );
else
document.write(1 + "<br>" );
}
let N = 4;
let arr = [8, 4, 6, 2];
minumumOperation(N, arr);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
02 Sep, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...