要附加的最小数字,使得 Array 的平均值等于 1
给定一个大小为N的数组arr[ ] ,任务是找到使数组arr[ ]的平均值等于 1 所需的最小操作数。在一个操作中,可以在数组末尾附加一个非负数。
例子:
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.
方法:上述问题可以借助数组总和和数组中元素的计数来解决,即N,根据以下情况:
- 如果数组总和小于 N,则可以将它们之间的差附加到数组中,因此需要 1 次操作。
- 如果数组总和等于 N,则均值将等于 1,因此需要 0 次操作。
- 如果数组总和大于 N,则可以在数组中追加 0 (arraySum – N) 次。因此需要 (arraySum – N) 操作。
请按照以下步骤解决问题:
- 求数组 arr[ ] 的总和,比如 sum_arr。
- 如果sum_arr >= N ,则打印sum_arr – N 。
- 否则打印1 。
下面是上述方法的实现。
C++
// C++ program for above approach
#include
using namespace std;
// Function to calculate minimum
// Number of operations
void minumumOperation(int N, int arr[]){
// Storing sum of array arr[]
int sum_arr = 0;
sum_arr = accumulate(arr, arr+N, sum_arr);
if(sum_arr >= N)
cout<
Java
// Java program for the above approach
import java.io.*;
class GFG
{
// Function to calculate minimum
// Number of operations
static void minumumOperation(int N, int arr[])
{
// Storing sum of array 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");
}
// Driver Code
public static void main(String[] args)
{
int N = 4;
int arr[] = {8, 4, 6, 2};
// Function Call
minumumOperation(N, arr);
}
}
// This code is contributed by dwivediyash
Python3
# Python program for above approach
# Function to calculate minimum
# Number of operations
def minumumOperation(N, arr):
# Storing sum of array arr[]
sum_arr = sum(arr)
if sum_arr >= N:
print(sum_arr-N)
else:
print(1)
# Driver Code
N = 4
arr = [8, 4, 6, 2]
# Function Call
minumumOperation(N, arr)
C#
// C# program for above approach
using System;
class GFG
{
// Function to calculate minimum
// Number of operations
static void minumumOperation(int N, int []arr){
// Storing sum of array 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);
}
// Driver Code
static public void Main (){
int N = 4;
int []arr = {8, 4, 6, 2};
// Function Call
minumumOperation(N, arr);
}
}
// This code is contributed by shivanisinghss2110
Javascript
输出
16
时间复杂度: O(N)
辅助空间: O(1)