Open In App

Minimizing Cost of Array Element Movement through Permutation

Last Updated : 12 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given two arrays, arr1[] of length m and arr2[] of length n, and an integer C. You can take any permutation of arr1[] and arr2[]. The task is to find the minimum cost by moving all elements from arr2[] to arr1[]. In each operation, remove arr2[0] and place it at the start of arr1[], and then move it to the right in arr1[] until it is smaller than the element to its right. Each swap is considered one operation and costs C.

Examples:

Input: m = 5, n = 3, C = 4, arr1[] = {10, 5, 2, 5, 4}, arr2[] = {3, 1, 2}
Output: 0
Explanation: One optimal permutation can be: arr1[]={10, 2, 5, 4, 5} and arr2[]={3, 2, 1}.

  • => Remove arr2[0] = 3 and insert into arr1, after this arr1 = {3, 10, 2, 5, 4, 5}
  • => Remove arr2[0] = 1 and insert into arr1, after this arr1 = {2, 3, 10, 2, 5, 4, 5}
  • => Remove arr2[0] = 2 and insert into arr1, after this arr1 = {1, 2, 3, 10, 2, 5, 4, 5}

Hence, there is no swapping required during moving all elements of arr2[] to arr1[]

Input: m = 3, n = 2, C = 5, arr1[] = {5, 4, 3}, arr2[] = {1, 10}
Output: 15
Explanation: One optimal permutation can be: arr1[] = {5, 4, 3} and arr2[] = {1, 10}.

  • => Remove arr2[0] = 1 and insert into arr1, after this arr1 = {1, 5, 4, 3}
  • => Remove arr2[0] = 10 and insert into arr1, after this arr1 = {1, 5, 4, 10}. Three swaps are required here.

Hence, there is total 3 swapping required during moving all elements of arr2[] to arr1[]. So, total cost would be 5*3 = 15

Approach:

The optimal strategy is to sort arr1[] in descending order. This ensures that the largest element comes first, minimizing the need for swaps when smaller elements are inserted. For example, if arr1[] = {1, 10} and arr2[] = {3}, without sorting arr1[], arr2[0] = 3 would require one swap to reach its correct position, resulting in arr1[] = {1, 3, 10}. However, if arr1[] is sorted in descending order, no swaps are needed and arr1[] becomes {3, 10, 1}.

Similarly, arr2[] should also be sorted in descending order. As elements are removed from arr2[] in decreasing order and inserted into arr1[], having arr2[] in descending order helps avoid any additional swaps.

Steps-by-step approach:

  • Sort arr1 and arr2 in descending order.
  • Initialize operations to 0.
  • Traverse through sorted arr2. If an element in arr2 is greater than the first element in arr1, increment operations by arr1.length (i.e, we have to put element of arr2 to the end of arr1).
  • Calculate minimum cost by multiplying operations with the given cost.
  • Print the calculated minimum cost.

Below is the code to implement the above approach:

C++
// Include necessary libraries
#include <bits/stdc++.h>
using namespace std;

// Function to calculate and print the minimum possible cost
void min_cost(long n, long m, vector<long> arr1,
              vector<long> arr2, long cost)
{
    // Sort arr1[] and arr2[] in descending order using the
    // in-built sort function
    sort(arr1.begin(), arr1.end(), greater<int>());
    sort(arr2.begin(), arr2.end(), greater<int>());

    // Initialize a variable to hold the number of minimum
    // operations needed
    long operations = 0;

    // Traverse through arr2[]
    for (int i = 0; i < arr2.size(); i++) {

        // If the current element in arr2[] is greater than
        // the first element in arr1[] increment the
        // operations count by n
        if (arr2[i] > arr1[0])
            operations += arr1.size();
        else
            continue; // If not, continue to the next
                      // iteration
    }

    // Print the minimum cost by multiplying the number of
    // operations with the cost per operation
    cout << operations * cost << endl;
}

// Driver code.
int main()
{

    // Define input variables
    long m = 3;
    long n = 2;
    long cost = 5;
    vector<long> arr1 = { 5, 4, 3 };
    vector<long> arr2 = { 10, 1 };

    // Call the function with the defined inputs
    min_cost(n, m, arr1, arr2, cost);
}
Java
import java.util.*;

public class Main {

    // Function to calculate and print the minimum possible
    // cost
    public static void min_cost(int n, int m,
                                ArrayList<Integer> arr1,
                                ArrayList<Integer> arr2,
                                int cost)
    {
        // Sort arr1[] and arr2[] in descending order using
        // the in-built sort function
        Collections.sort(arr1, Collections.reverseOrder());
        Collections.sort(arr2, Collections.reverseOrder());

        // Initialize a variable to hold the number of
        // minimum operations needed
        int operations = 0;

        // Traverse through arr2[]
        for (int i = 0; i < arr2.size(); i++) {

            // If the current element in arr2[] is greater
            // than the first element in arr1[] increment
            // the operations count by n
            if (arr2.get(i) > arr1.get(0))
                operations += arr1.size();
            else
                continue; // If not, continue to the next
                          // iteration
        }

        // Print the minimum cost by multiplying the number
        // of operations with the cost per operation
        System.out.println(operations * cost);
    }

    public static void main(String[] args)
    {
        // Define input variables
        int m = 3;
        int n = 2;
        int cost = 5;
        ArrayList<Integer> arr1
            = new ArrayList<>(Arrays.asList(5, 4, 3));
        ArrayList<Integer> arr2
            = new ArrayList<>(Arrays.asList(10, 1));

        // Call the function with the defined inputs
        min_cost(n, m, arr1, arr2, cost);
    }
}
Python
def min_cost(n, m, arr1, arr2, cost):
    # Sort arr1[] and arr2[] in descending order using the
    # in-built sorted function
    arr1.sort(reverse=True)
    arr2.sort(reverse=True)

    # Initialize a variable to hold the number of minimum
    # operations needed
    operations = 0

    # Traverse through arr2[]
    for i in range(len(arr2)):
        # If the current element in arr2[] is greater than
        # the first element in arr1[] increment the
        # operations count by n
        if arr2[i] > arr1[0]:
            operations += len(arr1)
        else:
            continue  # If not, continue to the next iteration

    # Print the minimum cost by multiplying the number of
    # operations with the cost per operation
    print(operations * cost)

# Driver code.
if __name__ == "__main__":
    # Define input variables
    m = 3
    n = 2
    cost = 5
    arr1 = [5, 4, 3]
    arr2 = [10, 1]

    # Call the function with the defined inputs
    min_cost(n, m, arr1, arr2, cost)
C#
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    // Function to calculate and print the minimum possible cost
    static void MinCost(long n, long m, List<long> arr1, List<long> arr2, long cost)
    {
        // Sort arr1[] and arr2[] in descending order
        arr1.Sort((a, b) => b.CompareTo(a));
        arr2.Sort((a, b) => b.CompareTo(a));

        // Initialize a variable to hold the number of minimum operations needed
        long operations = 0;

        // Traverse through arr2[]
        for (int i = 0; i < arr2.Count; i++)
        {
            // If the current element in arr2[] is greater than the first element in arr1[]
            // Increment the operations count by n
            if (arr2[i] > arr1[0])
                operations += arr1.Count;
            else
                continue; // If not, continue to the next iteration
        }

        // Print the minimum cost by multiplying the number of operations with the cost per operation
        Console.WriteLine(operations * cost);
    }

    // Driver code
    static void Main()
    {
        // Define input variables
        long m = 3;
        long n = 2;
        long cost = 5;
        List<long> arr1 = new List<long> { 5, 4, 3 };
        List<long> arr2 = new List<long> { 10, 1 };

        // Call the function with the defined inputs
        MinCost(n, m, arr1, arr2, cost);
    }
}
Javascript
// Function to calculate and print the minimum possible cost
function min_cost(n, m, arr1, arr2, cost) {
    // Sort arr1[] and arr2[] in descending order
    arr1.sort((a, b) => b - a);
    arr2.sort((a, b) => b - a);

    // Initialize a variable to hold the number of minimum operations needed
    let operations = 0;

    // Traverse through arr2[]
    for (let i = 0; i < arr2.length; i++) {
        // If the current element in arr2[] is greater than the first element in arr1[]
        // increment the operations count by n
        if (arr2[i] > arr1[0]) {
            operations += arr1.length;
        }
    }

    // Print the minimum cost by multiplying the number of operations with the cost per operation
    console.log(operations * cost);
}

// Define input variables
const m = 3;
const n = 2;
const cost = 5;
const arr1 = [5, 4, 3];
const arr2 = [10, 1];

// Call the function with the defined inputs
min_cost(n, m, arr1, arr2, cost);

Output
15



Time Complexity: O(max(n*log(n), m*log(m))
Auxiliary Space: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads