📌  相关文章
📜  在给定操作下数组的最大值和最小值之间的最小差

📅  最后修改于: 2021-04-27 20:14:39             🧑  作者: Mango

给定一个数组arr []和一个整数K。可以对任何数组元素执行以下操作:

  1. 将数组元素乘以K。
  2. 如果该元素可被K整除,则将其除以K。

上面的两个操作可以应用任何次数,包括在任何数组元素上的应用次数为零。任务是找到阵列的最大值和最小值之间的最小差异。
例子:

方法:想法是使用优先级队列作为多集。可以按照以下步骤计算答案:

  1. 最初,将所有可能的值(即,当数组元素乘以K,除以K时获得的值)与索引一起插入多重集。
  2. 从多集中连续弹出值。在每种情况下,具有索引i的弹出值X是最大值,并且如果对于所有索引都弹出了至少一个值,则当前答案将为X – min of(先前为索引弹出的值的最大值) ) ,除i以外的所有索引。
  3. 如果当前差异小于现在所计算的差异,请更新答案。
  4. 继续进行直到多重集中剩余元素。

下面是上述方法的实现:

C++
// C++ implementation of the above approach
#include
using namespace std;
 
// Function to calculate Minimum
// difference between maximum and
// minimum value of the array
int calculateMinDiff(int arr[], int k , int n)
{
     
    // Variable to store minimum difference
    int ans = INT_MAX;
 
    // PriorityQueue which is used as a multiset
    // to store all possible values
    priority_queue< pair > pq;
         
    // Iterate through all the values and
    // add it to the priority queue
    for (int i = 0; i < n; i++)
    {
 
        // If the number is divisible by k
        // divide it by K and add to priority queue
        if (arr[i] % k == 0)
            pq.push(make_pair( arr[i] / k, i ));
 
        // Adding number as it is
        pq.push(make_pair( arr[i], i ));
 
        // Adding number after multiplying it by k
        pq.push(make_pair(arr[i] * k, i ));
    }
 
    // HashMap to keep track of current values
 
    mapmp;
 
    while (!pq.empty())
    {
        pairtemp = pq.top();
        pq.pop();
        mp.insert(temp);
 
        // if for every index there is at-least
        // 1 value we calculate the answer
        if (mp.size() == n)
        {
            int min_value = INT_MAX;
 
            for(auto x:mp)
            min_value=min(min_value, x.second);
 
            ans = min(ans, temp.first - min_value);
        }
    }
 
    // Returning the calculated answer
     
    return ans;
}
 
// Driver code
int main()
{
    // Input Array
    int arr[7] = { 1, 2, 3, 4, 5, 10, 7 };
    int K = 5;
 
    // Size of the array
    int N = sizeof(arr)/sizeof(int);
 
    // Printing final output
    cout << (calculateMinDiff(arr, K, N));
}
 
// This code is contributed by ishayadav2918


Java
// Java implementation of the above approach
import java.io.*;
import java.util.*;
 
class GfG {
 
    // Function to calculate Minimum
    // difference between maximum and
    // minimum value of the array
    private static int calculateMinDiff(int arr[], int k)
    {
        // Length of the array
        int n = arr.length;
 
        // Variable to store minimum difference
        int ans = Integer.MAX_VALUE;
 
        // PriorityQueue which is used as a multiset
        // to store all possible values
        PriorityQueue pq
            = new PriorityQueue<>((int x[], int y[]) -> x[0] - y[0]);
 
        // Iterate through all the values and
        // add it to the priority queue
        for (int i = 0; i < n; i++) {
 
            // If the number is divisible by k
            // divide it by K and add to priority queue
            if (arr[i] % k == 0)
                pq.add(new int[] { arr[i] / k, i });
 
            // Adding number as it is
            pq.add(new int[] { arr[i], i });
 
            // Adding number after multiplying it by k
            pq.add(new int[] { arr[i] * k, i });
        }
 
        // HashMap to keep track of current values
        HashMap map = new HashMap<>();
 
        while (!pq.isEmpty()) {
            int temp[] = pq.poll();
            map.put(temp[1], temp[0]);
 
            // if for every index there is at-least
            // 1 value we calculate the answer
            if (map.size() == n) {
                ans = Math.min(ans,
                               temp[0]
                                   - Collections.min(map.values()));
            }
        }
 
        // Returning the calculated answer
        return ans;
    }
 
    // Driver code
    public static void main(String args[])
    {
        // Input Array
        int arr[] = { 1, 2, 3, 4, 5, 10, 7 };
        int K = 5;
 
        // Printing final output
        System.out.println(calculateMinDiff(arr, K));
    }
}


Python3
# Python3 implementation of the above approach 
import sys
 
# Function to calculate Minimum 
# difference between maximum and 
# minimum value of the array 
def calculateMinDiff(arr, k , n) : 
       
    # Variable to store minimum difference 
    ans = sys.maxsize
   
    # PriorityQueue which is used as a multiset 
    # to store all possible values 
    pq = []
           
    # Iterate through all the values and 
    # add it to the priority queue 
    for i in range(n) :
   
        # If the number is divisible by k 
        # divide it by K and add to priority queue 
        if (arr[i] % k == 0) :
            pq.append((arr[i] // k, i )) 
   
        # Adding number as it is 
        pq.append((arr[i], i)) 
   
        # Adding number after multiplying it by k 
        pq.append((arr[i] * k, i))
         
    pq.sort()
    pq.reverse()
   
    # HashMap to keep track of current values 
   
    mp = {} 
   
    while (len(pq) > 0) : 
     
        temp = pq[0] 
        pq.pop(0)
        mp[temp[0]] = temp[1] 
   
        # if for every index there is at-least 
        # 1 value we calculate the answer 
        if (len(mp) == n) :
         
            min_value = sys.maxsize
   
            for x in mp :
                min_value = min(min_value, mp[x])
   
            ans = min(ans, temp[0] - min_value - 1)
   
    # Returning the calculated answer 
       
    return ans
     
# Input Array 
arr = [ 1, 2, 3, 4, 5, 10, 7 ]
K = 5
 
# Size of the array 
N = len(arr)
 
# Printing final output 
print(calculateMinDiff(arr, K, N))
 
# This code is contributed by divyesh072019.


C#
// C# implementation of the above approach 
using System;
using System.Collections.Generic;
class GFG
{
 
  // Function to calculate Minimum 
  // difference between maximum and 
  // minimum value of the array 
  static int calculateMinDiff(int[] arr, int k , int n) 
  { 
 
    // Variable to store minimum difference 
    int ans = Int32.MaxValue; 
 
    // PriorityQueue which is used as a multiset 
    // to store all possible values 
    List> pq = new List>();
 
    // Iterate through all the values and 
    // add it to the priority queue 
    for (int i = 0; i < n; i++) 
    { 
 
      // If the number is divisible by k 
      // divide it by K and add to priority queue 
      if (arr[i] % k == 0) 
        pq.Add(new Tuple( arr[i] / k, i )); 
 
      // Adding number as it is 
      pq.Add(new Tuple( arr[i], i )); 
 
      // Adding number after multiplying it by k 
      pq.Add(new Tuple(arr[i] * k, i )); 
    }
 
    pq.Sort();
    pq.Reverse();
 
    // HashMap to keep track of current values 
    Dictionary mp = new Dictionary();
 
    while (pq.Count > 0) 
    { 
      Tuple temp = pq[0]; 
      pq.RemoveAt(0);
      mp[temp.Item1] = temp.Item2; 
 
      // if for every index there is at-least 
      // 1 value we calculate the answer 
      if (mp.Count == n)
      { 
        int min_value = Int32.MaxValue;
 
        foreach(KeyValuePair x in mp)
        {
          min_value=Math.Min(min_value, x.Value);
        }
 
        ans = Math.Min(ans, temp.Item1 - min_value - 1); 
      } 
    } 
 
    // Returning the calculated answer 
 
    return ans; 
  }
 
  // Driver code
  static void Main()
  {
 
    // Input Array 
    int[] arr = { 1, 2, 3, 4, 5, 10, 7 }; 
    int K = 5;
 
    // Size of the array 
    int N = arr.Length;
 
    // Printing final output
    Console.WriteLine(calculateMinDiff(arr, K, N));
  }
}
 
// This code is contributed by divyeshrabadiya07.


输出:
5

时间复杂度: O(NlogN)