📌  相关文章
📜  最小化 Pair 的递增或递增和递减,使所有 Array 元素相等

📅  最后修改于: 2022-05-13 01:56:04.854000             🧑  作者: Mango

最小化 Pair 的递增或递增和递减,使所有 Array 元素相等

给定一个大小为N的数组arr[] ,任务是通过执行以下操作来最小化步骤数以使所有数组元素相等:

  1. 选择数组的一个元素并将其增加 1。
  2. 同时选择两个元素 (arr[i], arr[j]) 将 arr[i] 加 1 并将 arr[j] 减 1。

例子

方法:这个问题可以使用基于以下思想的贪心方法来解决:

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

  • 对数组进行排序
  • 找出数组平均值的 ceil(比如avg )。
  • 现在从i = 0 遍历数组到 N-1
    • 每当您发现任何小于 avg 的元素时。
      • 从数组后端遍历,推导出大于avg的元素。
      • 最后,将avg-a[i]添加到答案中。
  • 返回答案。

下面是上述方法的实现:

C++
// C++ code to implement the approach
 
#include 
#define ll long long
#define mod 1000000007
using namespace std;
 
// function to find the minimum operations
// to make the array elements same
int findMinOperations(vector a, int n)
{
    ll avg = 0;
 
    // Sorting the array
    sort(a.begin(), a.end());
    for (int i : a) {
        avg += i;
    }
 
    // Finding out the average
 
    avg = avg % n == 0 ? avg / n : avg / n + 1;
    int i = 0, j = n - 1;
    int ans = 0;
 
    // Traversing the array
    while (i <= j) {
 
        // If current element is less than avg
        if (a[i] < avg) {
 
            // Total increments needed
            int incrementNeeded = avg - a[i];
            int k = incrementNeeded;
            a[i] = avg;
 
            // Traversing in the right side
            // of the array to find elements
            // which needs to be deduced to avg
            while (j > i && k > 0
                   && a[j] > avg) {
                int decrementNeeded
                    = a[j] - avg;
                if (k <= decrementNeeded) {
                    k -= decrementNeeded;
                }
                else {
                    a[j] -= k;
                    k = 0;
                }
                j--;
            }
 
            // Adding increments
            // needed to ans
            ans += incrementNeeded;
        }
        i++;
    }
    return ans;
}
 
// Driver Code
int main()
{
    vector A;
    A = { 1, 2, 3, 4 };
    int N = A.size();
    cout << findMinOperations(A, N);
    return 0;
}


Java
// Java code to implement the approach
import java.util.*;
public class GFG {
 
  // function to find the minimum operations
  // to make the array elements same
  static int findMinOperations(int[] a, int n)
  {
    long avg = 0;
 
    // Sorting the array
    Arrays.sort(a);
    for (int x = 0; x < a.length; x++) {
      avg += a[x];
    }
 
    // Finding out the average
    avg = avg % n == 0 ? avg / n : avg / n + 1;
    int i = 0, j = n - 1;
    int ans = 0;
 
    // Traversing the array
    while (i <= j) {
 
      // If current element is less than avg
      if (a[i] < avg) {
 
        // Total increments needed
        int incrementNeeded = (int)avg - a[i];
        int k = incrementNeeded;
        a[i] = (int)avg;
 
        // Traversing in the right side
        // of the array to find elements
        // which needs to be deduced to avg
        while (j > i && k > 0 && a[j] > avg) {
          int decrementNeeded = a[j] - (int)avg;
          if (k <= decrementNeeded) {
            k -= decrementNeeded;
          }
          else {
            a[j] -= k;
            k = 0;
          }
          j--;
        }
 
        // Adding increments
        // needed to ans
        ans += incrementNeeded;
      }
      i++;
    }
    return ans;
  }
 
  // Driver Code
  public static void main(String args[])
  {
    int[] A = { 1, 2, 3, 4 };
    int N = A.length;
    System.out.println(findMinOperations(A, N));
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Python3
# Python code to implement the approach
 
# function to find the minimum operations
# to make the array elements same
def findMinOperations(a, n):
    avg = 0
 
    # sorting the array
    a = sorted(a)
    avg = sum(a)
    # finding the average of the array
    if avg % n == 0:
        avg = avg//n
    else:
        avg = avg//n + 1
    i = 0
    j = n-1
    ans = 0
 
    # traverse the array
    while i <= j:
 
        # if current element is less than avg
        if a[i] < avg:
 
            # total increment needed
            incrementNeeded = avg - a[i]
            k = incrementNeeded
            a[i] = avg
 
            # Traversing in the right side
            # of the array to find elements
            # which needs to be deducted to avg
            while j > i and k > 0 and a[j] > avg:
                decrementNeeded = a[j] - avg
                if k <= decrementNeeded:
                    k -= decrementNeeded
                else:
                    a[j] -= k
                    k = 0
 
                j -= 1
            # Adding increments
            # needed to ans
            ans += incrementNeeded
        i += 1
    return ans
 
 
# Driver code
if __name__ == '__main__':
    a = [1, 2, 3, 4]
    n = len(a)
    print(findMinOperations(a, n))
 
    # This code is contributed by Amnindersingg1414.


C#
// C# code to implement the approach
using System;
class GFG
{
 
  // function to find the minimum operations
  // to make the array elements same
  static int findMinOperations(int []a, int n)
  {
    long avg = 0;
 
    // Sorting the array
    Array.Sort(a);
    for (int x = 0; x < a.Length; x++) {
      avg += a[x];
    }
 
    // Finding out the average
    avg = avg % n == 0 ? avg / n : avg / n + 1;
    int i = 0, j = n - 1;
    int ans = 0;
 
    // Traversing the array
    while (i <= j) {
 
      // If current element is less than avg
      if (a[i] < avg) {
 
        // Total increments needed
        int incrementNeeded = (int)avg - a[i];
        int k = incrementNeeded;
        a[i] = (int)avg;
 
        // Traversing in the right side
        // of the array to find elements
        // which needs to be deduced to avg
        while (j > i && k > 0
               && a[j] > avg) {
          int decrementNeeded
            = a[j] - (int)avg;
          if (k <= decrementNeeded) {
            k -= decrementNeeded;
          }
          else {
            a[j] -= k;
            k = 0;
          }
          j--;
        }
 
        // Adding increments
        // needed to ans
        ans += incrementNeeded;
      }
      i++;
    }
    return ans;
  }
 
  // Driver Code
  public static void Main()
  {
    int []A = { 1, 2, 3, 4 };
    int N = A.Length;
    Console.Write(findMinOperations(A, N));
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript



输出
3

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