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

📅  最后修改于: 2021-09-04 11:47:24             🧑  作者: 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


Javascript


输出:
5

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live