📌  相关文章
📜  通过增加和减少对来最小化使数组元素相等所需的移动 | 2套

📅  最后修改于: 2021-10-26 05:39:38             🧑  作者: Mango

给定一个大小为N的数组arr[] ,任务是通过选择任意一对不同的索引来打印使所有数组元素相等所需的最小移动次数,然后在第一个索引增加元素并在另一个索引处减少元素每次索引1 。如果不可能使所有数组元素相等,则打印“-1”。

例子:

朴素的方法:请参阅上一篇文章,了解解决问题的最简单方法。
时间复杂度: O(NlogN)
辅助空间: O(1)

高效的方法:上述方法可以基于以下观察进行优化:

  • 可以观察到,在每次操作中,数组的总和保持不变。因此,如果数组的和不可整除N ,则不可能使所有数组元素相等。
  • 否则,每个数组元素将等于数组的总和除以 N ,比如k
  • 因此,想法是遍历数组并找到当前元素与k之间的绝对差异并添加到ans
  • 由于在每个操作中,递增和递减都是一起执行的,因此ans / 2是所需的操作数。

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

  • 初始化一个变量,比如ans为 0,以存储所需操作的计数。
  • 找到数组的总和并将其存储在一个变量中,例如sum
  • 现在,如果总和不能被N整除,则打印“-1” 。否则,存储k = sum / N
  • 初始化变量,比如i = 0 ,然后遍历数组。
  • i小于N 时迭代并将当前元素和k之间的绝对差添加到ans
  • 最后,完成上述步骤后,打印ans / 2

下面是上述方法的实现:

C++
// cpp program for the above approach
 
// Function to find the minimum number
// of increment and decrement of pairs
// required to make all array elements equal
#include
using namespace std;
int find(vectorarr, int N)
{
 
    // Stores the sum of the array
    int Sum = 0;
    for(auto i:arr)
        Sum += i;
 
    // If sum is not divisible by N
    if (Sum % N)
        return -1;
   
   // Update sum
    int k = Sum / N;
    int ans = 0;
   
    // Store the minimum
    // number of operations
    int i = 0;
 
    // Iterate while i
    // is less than N
    while (i < N){
 
        // Add absolute difference
        // of current element with
        // k to ans
        ans = ans + abs(k-arr[i]);
       
        // Increase i bye 1
        i += 1;
    }
   
    // Return the value in ans//2
    return ans /2;
}
 
 
// Driver Code
int main()
{
   
    // Given Input
    vectorarr = {5, 4, 1, 10};
    int N = arr.size();
   
    // Function Call
    cout<<(find(arr, N));
}
 
// This code is contributed by amreshkumar3.


Java
// Java program for the above approach
import java.util.*;
 
class GFG
{
 
static int find(ArrayListarr, int N)
{
 
    // Stores the sum of the array
    int Sum = 0;
    for(int item : arr)
        Sum += item;
 
    // If sum is not divisible by N
    if (Sum % N==1)
        return -1;
   
   // Update sum
    int k = Sum / N;
    int ans = 0;
   
    // Store the minimum
    // number of operations
    int i = 0;
 
    // Iterate while i
    // is less than N
    while (i < N){
 
        // Add absolute difference
        // of current element with
        // k to ans
        ans = ans + Math.abs(k-arr.get(i));
       
        // Increase i bye 1
        i += 1;
    }
   
    // Return the value in ans//2
    return ans /2;
}
 
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given Input
    ArrayListarr = new ArrayList<>();
    arr.add(5);
    arr.add(4);
    arr.add(1);
    arr.add(10);
     
    int N = arr.size();
   
    // Function Call
    System.out.println(find(arr, N));
    }
}
 
// This code is contributed by sanjoy_62.


Python3
# Python program for the above approach
 
# Function to find the minimum number
# of increment and decrement of pairs
# required to make all array elements equal
def find(arr, N):
 
    # Stores the sum of the array
    Sum = sum(arr)
 
    # If sum is not divisible by N
    if Sum % N:
        return -1
    else:
 
       # Update sum
        k = Sum // N
 
        # Store the minimum
        # number of operations
        ans = 0
 
        i = 0
 
        # Iterate while i
        # is less than N
        while i < N:
 
            # Add absolute difference
            # of current element with
            # k to ans
            ans = ans + abs(k-arr[i])
 
            # Increase i bye 1
            i += 1
 
        # Return the value in ans//2
        return ans // 2
 
 
# Driver Code
if __name__ == '__main__':
 
    # Given Input
    arr = [5, 4, 1, 10]
    N = len(arr)
 
    # Function Call
    print(find(arr, N))


C#
// C# program for the above approach
 
// Function to find the minimum number
// of increment and decrement of pairs
// required to make all array elements equal
using System;
using System.Collections.Generic;
 
class GFG{
 
static int find(Listarr, int N)
{
 
    // Stores the sum of the array
    int Sum = 0;
    foreach(int item in arr)
        Sum += item;
 
    // If sum is not divisible by N
    if (Sum % N==1)
        return -1;
   
   // Update sum
    int k = Sum / N;
    int ans = 0;
   
    // Store the minimum
    // number of operations
    int i = 0;
 
    // Iterate while i
    // is less than N
    while (i < N){
 
        // Add absolute difference
        // of current element with
        // k to ans
        ans = ans + Math.Abs(k-arr[i]);
       
        // Increase i bye 1
        i += 1;
    }
   
    // Return the value in ans//2
    return ans /2;
}
 
 
// Driver Code
public static void Main()
{
   
    // Given Input
    Listarr = new List(){5, 4, 1, 10};
    int N = arr.Count;
   
    // Function Call
    Console.Write(find(arr, N));
}
}
 
// This code is contributed by bgangwar59.


Javascript


输出:
5

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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程