📌  相关文章
📜  最小化减法,然后是使所有数组元素相等所需的相邻元素的增量

📅  最后修改于: 2021-09-03 03:29:27             🧑  作者: Mango

给定一个由N 个正整数组成的数组arr[] ,任务是通过重复从任意数量的数组元素中减去 1并同时将其添加到相邻元素之一,使所有数组元素相等。如果不能使所有数组元素相等,则打印“-1” 。否则,打印所需的最小操作数。

例子:

方法:根据以下观察可以解决给定的问题:

  • 当且仅当所有数组元素的值等于数组的平均值时,才能使所有数组元素相等。
  • 由于一次只能从数组元素中减去1 ,因此最小移动次数是数组前缀和的最大值或使每个元素等于数组平均值所需的移动次数。

请按照以下步骤解决问题:

  • 计算数组arr[]元素的总和,比如S
  • 如果总和S不能被N整除,则打印“-1”
  • 否则,执行以下操作:
    • 将数组元素的平均值存储在一个变量中,比如avg
    • 0初始化两个变量,比如totalcount ,分别存储所需的结果和最小移动的前缀和,以实现avg
    • 遍历给定的数组arr[]并执行以下步骤:
      • (arr[i] – avg)的值添加到计数中
      • total的值更新为counttotal(arr[i] – avg)绝对值的最大值。
  • 完成上述步骤后,打印total的值作为所需的最小运算结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the minimum number
// of moves required to make all array
// elements equal
int findMinMoves(int arr[], int N)
{
    // Store the total sum of the array
    int sum = 0;
 
    // Calculate total sum of the array
    for (int i = 0; i < N; i++)
        sum += arr[i];
 
    // If the sum is not divisible
    // by N, then print "-1"
    if (sum % N != 0)
        return -1;
 
    // Stores the average
    int avg = sum / N;
 
    // Stores the count
    // of operations
    int total = 0;
 
    int needCount = 0;
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++) {
 
        // Update number of moves
        // required to make current
        // element equal to avg
        needCount += (arr[i] - avg);
 
        // Update the overall count
        total
            = max(max(abs(needCount),
                      arr[i] - avg),
                  total);
    }
 
    // Return the minimum
    // operations required
    return total;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 0, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << findMinMoves(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG{
 
// Function to find the minimum number
// of moves required to make all array
// elements equal
static int findMinMoves(int[] arr, int N)
{
     
    // Store the total sum of the array
    int sum = 0;
 
    // Calculate total sum of the array
    for(int i = 0; i < N; i++)
        sum += arr[i];
 
    // If the sum is not divisible
    // by N, then print "-1"
    if (sum % N != 0)
        return -1;
 
    // Stores the average
    int avg = sum / N;
 
    // Stores the count
    // of operations
    int total = 0;
 
    int needCount = 0;
 
    // Traverse the array arr[]
    for(int i = 0; i < N; i++)
    {
         
        // Update number of moves
        // required to make current
        // element equal to avg
        needCount += (arr[i] - avg);
 
        // Update the overall count
        total = Math.max(
            Math.max(Math.abs(needCount),
                     arr[i] - avg), total);
    }
 
    // Return the minimum
    // operations required
    return total;
}
 
// Driver Code
public static void main(String[] args)
{
    int[] arr = { 1, 0, 5 };
    int N = arr.length;
     
    System.out.println(findMinMoves(arr, N));
}
}
 
// This code is contributed by sanjoy_62


Python3
# Python3 program for the above approach
 
# Function to find the minimum number
# of moves required to make all array
# elements equal
def findMinMoves(arr, N):
   
    # Store the total sum of the array
    sum = 0
 
    # Calculate total sum of the array
    for i in range(N):
        sum += arr[i]
 
    # If the sum is not divisible
    # by N, then print "-1"
    if(sum % N != 0):
        return -1
 
    # Stores the average
    avg = sum // N
 
    # Stores the count
    # of operations
    total = 0
    needCount = 0
 
    # Traverse the array arr[]
    for i in range(N):
       
        # Update number of moves
        # required to make current
        # element equal to avg
        needCount += (arr[i] - avg)
 
        # Update the overall count
        total = max(max(abs(needCount), arr[i] - avg), total)
 
    # Return the minimum
    # operations required
    return total
 
# Driver Code
if __name__ == '__main__':
    arr =  [1, 0, 5]
    N =  len(arr)
    print(findMinMoves(arr, N))
 
    # This code is contributed by bgangwar59.


C#
// C# program for the above approach
using System;
 
class GFG{
     
// Function to find the minimum number
// of moves required to make all array
// elements equal
static int findMinMoves(int[] arr, int N)
{
     
    // Store the total sum of the array
    int sum = 0;
 
    // Calculate total sum of the array
    for(int i = 0; i < N; i++)
        sum += arr[i];
 
    // If the sum is not divisible
    // by N, then print "-1"
    if (sum % N != 0)
        return -1;
 
    // Stores the average
    int avg = sum / N;
 
    // Stores the count
    // of operations
    int total = 0;
 
    int needCount = 0;
 
    // Traverse the array arr[]
    for(int i = 0; i < N; i++)
    {
         
        // Update number of moves
        // required to make current
        // element equal to avg
        needCount += (arr[i] - avg);
 
        // Update the overall count
        total = Math.Max(
            Math.Max(Math.Abs(needCount),
                     arr[i] - avg), total);
    }
 
    // Return the minimum
    // operations required
    return total;
}
 
// Driver Code
public static void Main()
{
    int[] arr = { 1, 0, 5 };
    int N = arr.Length;
     
    Console.Write(findMinMoves(arr, N));
}
}
 
// This code is contributed by ukasp


Javascript


输出:
3

时间复杂度: O(N)
辅助空间: O(1)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live