📌  相关文章
📜  通过给定的操作最小化数组的偏差

📅  最后修改于: 2021-04-17 17:03:22             🧑  作者: Mango

给定一个由正整数组成的数组A [] ,任务是在多次执行以下运算后,计算给定数组A []的最小可能偏差:

  • 操作1:如果数组元素为偶数,则将其除以2
  • 操作2:如果数组元素为奇数,则将其乘以2

数组A []的偏差是在该阵列A中的最大和最小元件本之间的差[]。

例子:

方法:可以根据以下观察结果解决问题:

  • 偶数可以被除以多次,直到转换为奇数为止。
  • 奇数转换为偶数时只能加倍一次。
  • 因此,偶数永远不会增加。

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

  • 遍历数组并将所有奇数数组元素加倍。这使第二次操作的要求无效。
  • 现在,减少最大的数组元素,使其均匀。
  • 要以排序方式存储数组元素,请将所有数组元素插入Set中。
  • 贪婪地减少集合中存在的最大元素
  • 如果集合中存在的最大元素为奇数,请中断循环。
  • 打印获得的最小偏差。

下面是上述方法的实现:

C++
// C++ implementation of the
// above approach
 
#include 
using namespace std;
 
// Function to find the minimum
// deviation of the array A[]
void minimumDeviation(int A[], int N)
{
    // Store all array elements
    // in sorted order
    set s;
 
    for (int i = 0; i < N; i++) {
 
        if (A[i] % 2 == 0)
            s.insert(A[i]);
 
        // Odd number are transformed
        // using 2nd operation
        else
            s.insert(2 * A[i]);
    }
 
    // (Maximum - Minimum)
    int diff = *s.rbegin() - *s.begin();
 
    // Check if the size of set is > 0 and
    // the maximum element is divisible by 2
    while ((int)s.size()
           && *s.rbegin() % 2 == 0) {
 
        // Maximum element of the set
        int maxEl = *s.rbegin();
 
        // Erase the maximum element
        s.erase(maxEl);
 
        // Using operation 1
        s.insert(maxEl / 2);
 
        // (Maximum - Minimum)
        diff = min(diff, *s.rbegin() - *s.begin());
    }
 
    // Print the Minimum
    // Deviation Obtained
    cout << diff;
}
 
// Driver Code
int main()
{
    int A[] = { 4, 1, 5, 20, 3 };
    int N = sizeof(A) / sizeof(A[0]);
 
    // Function Call to find
    // Minimum Deviation of A[]
    minimumDeviation(A, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG
{
 
// Function to find the minimum
// deviation of the array A[]
static void minimumDeviation(int A[], int N)
{
   
    // Store all array elements
    // in sorted order
    TreeSet s = new TreeSet();
    for (int i = 0; i < N; i++)
    {
 
        if (A[i] % 2 == 0)
            s.add(A[i]);
 
        // Odd number are transformed
        // using 2nd operation
        else
            s.add(2 * A[i]);
    }
 
    // (Maximum - Minimum)
    int diff =  s.last() -  s.first() ;
 
    // Check if the size of set is > 0 and
    // the maximum element is divisible by 2
    while ((s.last() % 2 == 0))
    {
 
        // Maximum element of the set
        int maxEl = s.last();
 
        // Erase the maximum element
        s.remove(maxEl);
 
        // Using operation 1
        s.add(maxEl / 2);
 
        // (Maximum - Minimum)
        diff = Math.min(diff, s.last() -  s.first());
    }
 
    // Print the Minimum
    // Deviation Obtained
    System.out.print(diff);
}
 
// Driver code
public static void main(String[] args)
{
    int A[] = { 4, 1, 5, 20, 3 };
    int N = A.length;
 
    // Function Call to find
    // Minimum Deviation of A[]
    minimumDeviation(A, N);
}
}
 
// This code is contributed by susmitakundugoaldanga.


Python3
# Python 3 implementation of the
# above approach
 
# Function to find the minimum
# deviation of the array A[]
def minimumDeviation(A, N):
 
    # Store all array elements
    # in sorted order
    s = set([])
 
    for i in range(N):
        if (A[i] % 2 == 0):
            s.add(A[i])
 
        # Odd number are transformed
        # using 2nd operation
        else:
            s.add(2 * A[i])
 
    # (Maximum - Minimum)
 
    s = list(s)
    diff = s[-1] - s[0]
 
    # Check if the size of set is > 0 and
    # the maximum element is divisible by 2
    while (len(s) and s[-1] % 2 == 0):
 
        # Maximum element of the set
        maxEl = s[-1]
 
        # Erase the maximum element
        s.remove(maxEl)
 
        # Using operation 1
        s.append(maxEl // 2)
 
        # (Maximum - Minimum)
        diff = min(diff, s[-1] - s[0])
 
    # Print the Minimum
    # Deviation Obtained
    print(diff)
 
# Driver Code
if __name__ == "__main__":
    A = [4, 1, 5, 20, 3]
    N = len(A)
 
    # Function Call to find
    # Minimum Deviation of A[]
    minimumDeviation(A, N)
 
    # This code is contributed by chitranayal.


C#
// C# implementation of the
// above approach
using System;
using System.Collections.Generic;
using System.Linq;
class GFG
{
     
    // Function to find the minimum
    // deviation of the array A[]
    static void minimumDeviation(int[] A, int N)
    {
       
        // Store all array elements
        // in sorted order
        HashSet s = new HashSet();
        for (int i = 0; i < N; i++)
        {
            if (A[i] % 2 == 0)
                s.Add(A[i]);
      
            // Odd number are transformed
            // using 2nd operation
            else
                s.Add(2 * A[i]);
        }
        List S = s.ToList();
        S.Sort();
      
        // (Maximum - Minimum)
        int diff = S[S.Count - 1] - S[0];
      
        // Check if the size of set is > 0 and
        // the maximum element is divisible by 2
        while ((int)S.Count != 0 && S[S.Count - 1] % 2 == 0) {
      
            // Maximum element of the set
            int maxEl = S[S.Count - 1];
      
            // Erase the maximum element
            S.RemoveAt(S.Count - 1);
      
            // Using operation 1
            S.Add(maxEl / 2);
             
            S.Sort();
      
            // (Maximum - Minimum)
            diff = Math.Min(diff, S[S.Count - 1] - S[0]);
        }
      
        // Print the Minimum
        // Deviation Obtained
        Console.Write(diff);
    }
 
  // Driver code
  static void Main()
  {
    int[] A = { 4, 1, 5, 20, 3 };
    int N = A.Length;
  
    // Function Call to find
    // Minimum Deviation of A[]
    minimumDeviation(A, N);
  }
}
 
// This code is contributed by divyeshrabadiya07.


输出:
3

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