📌  相关文章
📜  分配给元素的最小值,以使总和大于初始总和

📅  最后修改于: 2021-05-04 09:11:30             🧑  作者: Mango

给定一个由N个元素组成的数组arr [] ,任务是将给定数组的所有元素更新为某个值X ,以使所有更新后的数组元素的和严格大于初始数组中所有元素的和。 X最小可能。

例子:

方法:

  • 找到原始数组元素的总和并将其存储在变量sumArr中
  • 计算X = sumArr / n ,其中n是数组中元素的数量。
  • 现在,为了超过原始数组的总和,新数组的每个元素必须至少为X + 1

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to return the minimum
// required value
int findMinValue(int arr[], int n)
{
  
    // Find the sum of the
    // array elements
    long sum = 0;
    for (int i = 0; i < n; i++)
        sum += arr[i];
  
    // Return the required value
    return ((sum / n) + 1);
}
  
// Driver code
int main()
{
    int arr[] = { 4, 2, 1, 10, 6 };
    int n = sizeof(arr) / sizeof(int);
  
    cout << findMinValue(arr, n);
  
    return 0;
}


Java
// Java implementation of the approach
class GFG {
  
    // Function to return the minimum
    // required value
    static int findMinValue(int arr[], int n)
    {
  
        // Find the sum of the
        // array elements
        long sum = 0;
        for (int i = 0; i < n; i++)
            sum += arr[i];
  
        // Return the required value
        return ((int)(sum / n) + 1);
    }
  
    // Driver code
    public static void main(String args[])
    {
        int arr[] = { 4, 2, 1, 10, 6 };
        int n = arr.length;
  
        System.out.print(findMinValue(arr, n));
    }
}


Python3
# Python3 implementation of the approach
  
# Function to return the minimum 
# required value
def findMinValue(arr, n):
      
    # Find the sum of the 
    # array elements
    sum = 0
    for i in range(n):
        sum += arr[i]
          
    # Return the required value
    return (sum // n) + 1
      
# Driver code
arr = [4, 2, 1, 10, 6] 
n = len(arr) 
print(findMinValue(arr, n))


C#
// C# implementation of the above approach
using System;
  
class GFG
{ 
      
    // Function to return the minimum 
    // required value 
    static int findMinValue(int []arr, int n) 
    { 
  
        // Find the sum of the 
        // array elements 
        long sum = 0; 
        for (int i = 0; i < n; i++) 
            sum += arr[i]; 
  
        // Return the required value 
        return ((int)(sum / n) + 1); 
    } 
  
    // Driver code 
    static public void Main () 
    { 
        int []arr = { 4, 2, 1, 10, 6 }; 
        int n = arr.Length; 
  
        Console.WriteLine(findMinValue(arr, n)); 
    } 
}        
          
// This code is contributed by AnkitRai01


输出:
5