📌  相关文章
📜  最小化交换两个给定阵列的成本

📅  最后修改于: 2021-05-17 04:16:28             🧑  作者: Mango

给定两个大小均为N的数组A []B []由不同的元素组成,任务是找到交换两个给定数组的最小开销。交换两个元素A [i]B [j]的成本为min(A [i],A [j]) 。总成本是所有交换操作成本的累积总和。

注意:这里,元素的顺序可以与交换后的原始数组不同。

例子:

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

  • 同时遍历数组并从中找到最小元素,例如K。
  • 现在,每个具有K的元素都将交换到两个数组中。因此,所需的交换数量为2 * N – 1
  • 打印K *(2 * N – 1)作为答案。

下面是上述方法的实现:

C++
// C++ program to implement
// the above appraoch
#include 
using namespace std;
 
// Function to calculate and return the
// minimum cost required to swap two arrays
int getMinCost(vector A, vector B,
               int N)
{
 
    int mini = INT_MAX;
    for (int i = 0; i < N; i++) {
        mini = min(mini, min(A[i], B[i]));
    }
 
    // Return the total minimum cost
    return mini * (2 * N - 1);
}
 
// Driver Code
int main()
{
    int N = 3;
 
    vector A = { 1, 4, 2 };
    vector B = { 10, 6, 12 };
 
    cout << getMinCost(A, B, N);
    return 0;
}


Java
// Java program to implement
// the above appraoch
class GFG{
 
// Function to calculate and return the
// minimum cost required to swap two arrays
static int getMinCost(int [] A, int [] B,
                                   int N)
{
    int mini = Integer.MAX_VALUE;
    for (int i = 0; i < N; i++)
    {
        mini = Math.min(mini,
               Math.min(A[i], B[i]));
    }
 
    // Return the total minimum cost
    return mini * (2 * N - 1);
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 3;
 
    int [] A = { 1, 4, 2 };
    int [] B = { 10, 6, 12 };
 
    System.out.print(getMinCost(A, B, N));
}
}
 
// This code is contributed by sapnasingh4991


Python3
# Python3 program to implement
# the above appraoch
import sys
 
# Function to calculate and return the
# minimum cost required to swap two arrays
def getMinCost(A, B, N):
 
    mini = sys.maxsize
    for i in range(N):
        mini = min(mini, min(A[i], B[i]))
 
    # Return the total minimum cost
    return mini * (2 * N - 1)
 
# Driver Code
N = 3
 
A = [ 1, 4, 2 ]
B = [ 10, 6, 12 ]
 
print(getMinCost(A, B, N))
 
# This code is contributed by chitranayal


C#
// C# program to implement
// the above appraoch
using System;
class GFG{
 
    // Function to calculate and return the
    // minimum cost required to swap two arrays
    static int getMinCost(int[] A, int[] B, int N)
    {
        int mini = int.MaxValue;
        for (int i = 0; i < N; i++)
        {
            mini = Math.Min(mini, Math.Min(A[i], B[i]));
        }
 
        // Return the total minimum cost
        return mini * (2 * N - 1);
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int N = 3;
          int[] A = {1, 4, 2};
        int[] B = {10, 6, 12};
          Console.Write(getMinCost(A, B, N));
    }
}
 
// This code is contributed by shikhasingrajput


输出:
5




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