Given an array arr[] of N elements, the task is to update all the elements of the given array to some value X such that the sum of all the updated array elements is strictly greater than the sum of all the elements of the initial array and X is the minimum possible.
Examples:
Input: arr[] = {4, 2, 1, 10, 6}
Output: 5
Sum of original array = 4 + 2 + 1 + 10 + 6 = 23
Sum of the modified array = 5 + 5 + 5 + 5 + 5 = 25
Input: arr[] = {9876, 8654, 5470, 3567, 7954}
Output: 7105
Approach:
- Find the sum of the original array elements and store it in a variable sumArr
- Calculate X = sumArr / n where n is the number of elements in the array.
- Now, in order to exceed the sum of the original array, every element of the new array has to be at least X + 1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findMinValue( int arr[], int n)
{
long sum = 0;
for ( int i = 0; i < n; i++)
sum += arr[i];
return ((sum / n) + 1);
}
int main()
{
int arr[] = { 4, 2, 1, 10, 6 };
int n = sizeof (arr) / sizeof ( int );
cout << findMinValue(arr, n);
return 0;
}
|
Java
import java.io.*;
public class GFG {
static int findMinValue( int arr[], int n)
{
long sum = 0 ;
for ( int i = 0 ; i < n; i++)
sum += arr[i];
return (( int )(sum / n) + 1 );
}
public static void main(String args[])
{
int arr[] = { 4 , 2 , 1 , 10 , 6 };
int n = arr.length;
System.out.print(findMinValue(arr, n));
}
}
|
Python3
def findMinValue(arr, n):
sum = 0
for i in range (n):
sum + = arr[i]
return ( sum / / n) + 1
arr = [ 4 , 2 , 1 , 10 , 6 ]
n = len (arr)
print (findMinValue(arr, n))
|
C#
using System;
class GFG
{
static int findMinValue( int []arr, int n)
{
long sum = 0;
for ( int i = 0; i < n; i++)
sum += arr[i];
return (( int )(sum / n) + 1);
}
static public void Main ()
{
int []arr = { 4, 2, 1, 10, 6 };
int n = arr.Length;
Console.WriteLine(findMinValue(arr, n));
}
}
|
Javascript
<script>
function findMinValue(arr, n)
{
let sum = 0;
for (let i = 0; i < n; i++)
sum += arr[i];
return (parseInt(sum / n) + 1);
}
let arr = [ 4, 2, 1, 10, 6 ];
let n = arr.length;
document.write(findMinValue(arr, n));
</script>
|
Time Complexity: O(N).
Auxiliary Space: O(1).