📌  相关文章
📜  通过增加和减少对来最小化移动以使 Array 元素相等

📅  最后修改于: 2021-10-26 02:27:22             🧑  作者: Mango

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

例子

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

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

  • 初始化一个变量,比如ans0 ,以存储所需移动的计数。
  • 找到数组的总和并将其存储在一个变量中,比如sum
  • 现在,如果总和不能被N整除,则打印“ -1 ”。否则,将总和更新为sum = sum/N。
  • 按升序对数组进行排序。
  • 初始化变量,比如i0jN – 1以迭代数组。
  • 迭代直到i小于 j 并执行以下步骤:
    • 如果arr[i]增加到sum小于将arr[j]减少到sum ,则将sum – arr[i] 添加ans ,然后更新arr[i]arr[j] ,然后将i增加1
    • 否则,将arr[j] – sum添加到ans ,并更新arr[i]arr[j] ,然后将j1。
  • 最后,完成上述步骤后,打印ans中存储的值。

下面是上述方法的实现:

C++
// C++ Program for the above approach
#include 
#include 
using namespace std;
 
// Function to find the minimum
// operations to make the array
// elements equal
int find(int arr[], int N)
{
  // Stores the sum of the
  // array
  int Sum = 0;
  for (int i = 0; i < N; i++) {
    Sum += arr[i];
  }
  if (Sum % N) {
    return -1;
  }
 
  // update sum
  Sum /= N;
 
  // sort array
  sort(arr, arr + N);
 
  // Store the minimum
  // needed moves
  int ans = 0;
  int i = 0, j = N - 1;
 
  // Iterate until i
  // is less than j
  while (i < j) {
    if (Sum - arr[i] < arr[j] - Sum) {
 
      // Increment ans by
      // Sum-arr[i]
      ans += (Sum - arr[i]);
 
      // update
      arr[i] += (Sum - arr[i]);
      arr[j] -= (Sum - arr[i]);
 
      // Increment i by 1
      i++;
    }
    else {
 
      // Increment ans by
      //arr[j]-Sum
      ans += (arr[j] - Sum);
 
      // Update
      arr[i] += (arr[j] - Sum);
      arr[j] -= (arr[j] - Sum);
 
      // Decrement j by 1
      j--;
    }
  }
 
  // Return the value in ans
  return ans;
}
 
// Driver code
int main()
{
 
  // Given input
  int arr[] = { 5, 4, 1, 10 };
  int N = sizeof(arr) / sizeof(int);
 
  // Function call
  cout << find(arr, N);
  return 0;
}
 
// This code is contributed by Parth Manchanda


Java
import java.util.Arrays;
 
// Java Program for the above approach
 
class GFG {
 
    // Function to find the minimum
    // operations to make the array
    // elements equal
    public static int find(int arr[], int N)
    {
       
        // Stores the sum of the
        // array
        int Sum = 0;
        for (int i = 0; i < N; i++) {
            Sum += arr[i];
        }
        if (Sum % N > 0) {
            return -1;
        }
 
        // update sum
        Sum /= N;
 
        // sort array
        Arrays.sort(arr);
 
        // Store the minimum
        // needed moves
        int ans = 0;
        int i = 0, j = N - 1;
 
        // Iterate until i
        // is less than j
        while (i < j) {
            if (Sum - arr[i] < arr[j] - Sum) {
 
                // Increment ans by
                // Sum-arr[i]
                ans += (Sum - arr[i]);
 
                // update
                arr[i] += (Sum - arr[i]);
                arr[j] -= (Sum - arr[i]);
 
                // Increment i by 1
                i++;
            } else {
 
                // Increment ans by
                // arr[j]-Sum
                ans += (arr[j] - Sum);
 
                // Update
                arr[i] += (arr[j] - Sum);
                arr[j] -= (arr[j] - Sum);
 
                // Decrement j by 1
                j--;
            }
        }
 
        // Return the value in ans
        return ans;
    }
 
    // Driver code
    public static void main(String args[]) {
 
        // Given input
        int arr[] = { 5, 4, 1, 10 };
        int N = arr.length;
 
        // Function call
        System.out.println(find(arr, N));
 
    }
}
 
// This code is contributed by gfgking


Python3
# Python program for the above approach
 
# Function to find the minimum
# operations to make the 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
        Sum //= N
 
        # Sort the array
        arr.sort()
 
        # Store the minimum
        # needed moves
        ans = 0
 
        i = 0
        j = N-1
 
        # Iterate until i
        # is less than j
        while i < j:
 
            # If the Sum-arr[i]
            # is less than the
            # arr[j]-sum
            if Sum-arr[i] < arr[j]-Sum:
 
                # Increment ans by
                # Sum-arr[i]
                ans += Sum-arr[i]
 
                # Update
                arr[i] += Sum-arr[i]
                arr[j] -= Sum-arr[i]
 
                # Increment i by 1
                i += 1
                 
            # Otherwise,
            else:
 
                # Increment ans by
                # arr[j]-Sum
                ans += arr[j]-Sum
 
                # Update
                arr[i] += arr[j]-Sum
                arr[j] -= arr[j]-Sum
 
                # Decrement j by 1
                j -= 1
 
        # Return the value in ans
        return ans
 
# 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
using System;
 
class GFG{
     
// Function to find the minimum
// operations to make the array
// elements equal
public static int find(int[] arr, int N)
{
     
    // Stores the sum of the
    // array
    int Sum = 0;
    int i = 0;
     
    for(i = 0; i < N; i++)
    {
        Sum += arr[i];
    }
    if (Sum % N > 0)
    {
        return -1;
    }
 
    // update sum
    Sum /= N;
 
    // sort array
    Array.Sort(arr);
 
    // Store the minimum
    // needed moves
    int ans = 0;
    i = 0;
    int j = N - 1;
 
    // Iterate until i
    // is less than j
    while (i < j)
    {
        if (Sum - arr[i] < arr[j] - Sum)
        {
             
            // Increment ans by
            // Sum-arr[i]
            ans += (Sum - arr[i]);
 
            // update
            arr[i] += (Sum - arr[i]);
            arr[j] -= (Sum - arr[i]);
 
            // Increment i by 1
            i++;
        }
        else
        {
             
            // Increment ans by
            // arr[j]-Sum
            ans += (arr[j] - Sum);
 
            // Update
            arr[i] += (arr[j] - Sum);
            arr[j] -= (arr[j] - Sum);
 
            // Decrement j by 1
            j--;
        }
    }
 
    // Return the value in ans
    return ans;
}
 
// Driver code
static public void Main()
{
     
    // Given input
    int[] arr = { 5, 4, 1, 10 };
    int N = arr.Length;
 
    // Function call
    Console.WriteLine(find(arr, N));
}
}
 
// This code is contributed by target_2


Javascript


输出
5

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

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