Minimum cost to merge numbers from 1 to N

Given an integer N, the task is to find the minimum cost to merge all the numbers from 1 to N where the cost of merging two set of numbers A and B is equal to the product of the product of the numbers in the respective sets.
Examples:Â Â
Input: N = 4Â
Output: 32
Merging {1} and {2} costs 1 * 2 = 2Â
Merging {1, 2} and {3} costs 2 * 3 = 6Â
Merge{1, 2, 3} and {4} costs 6 * 4 = 24Â
Hence, the minimal cost is 2 + 6 + 24 = 32Input: N = 2Â
Output: 2Â
Approach:Â
- The first approach that comes in our mind is sorting. We take first two smallest elements and add them, then continue adding to the rest of the elements in the sorted array. But it fails when the current running sum exceeds the next smallest value in the array coming next.
Take N = 5,
If we take the sorting approach, then-
Merge {1} and {2} - 1 * 2 = 2
Merge {1, 2} and {3} - 2 * 3 = 6
Merge{1, 2, 3} and {4} - 6 * 4 = 24
Merge{1, 2, 3, 4} and {5} - 24 * 5 = 120
Total sum = 152
But optimal way is,
Merge {1} and {2} - 1 * 2 = 2
Merge {1, 2} and {3} - 2 * 3 = 6
Merge {4} and {5} - 4 * 5 = 20
Merge {1, 2, 3} and {4, 5} - 6 * 20 = 120
Total sum = 148
This is the minimal answer.
- So, the correct approach to solve this problem is the Min-heap based approach. Initially, we push all the numbers from 1 to N into the Min-Heap.
- At every iteration, we extract the minimum and the second minimum element from the Min-Heap and insert their product back into it. This ensures that the addition cost generated will be minimum.
- We keep on repeating the above step until there is only one element remaining in the Min-Heap. The calculated sum till that instant gives us the required answer.
Below is the implementation of the above approach:Â
C++
// C++ program to find the Minimum // cost to merge numbers // from 1 to N.#include <bits/stdc++.h>using namespace std;Â
// Function returns the // minimum costint GetMinCost(int N){Â
    // Min Heap representation    priority_queue<int, vector<int>,                   greater<int> > pq;Â
    // Add all elements to heap    for (int i = 1; i <= N; i++) {        pq.push(i);    }         int cost = 0;         while (pq.size() > 1)    {        // First minimum        int mini = pq.top();        pq.pop();Â
        // Second minimum        int secondmini = pq.top();        pq.pop();Â
        // Multiply them        int current = mini * secondmini;Â
        // Add to the cost        cost += current;Â
        // Push the product into the        // heap again        pq.push(current);    }Â
    // Return the optimal cost    return cost;}Â
// Driver codeint main(){Â Â Â Â int N = 5;Â Â Â Â cout << GetMinCost(N);} |
Java
// Java program for the above approach import java.util.*;Â
class GFG {Â
// Function returns the // minimum cost static int GetMinCost(int N){Â
    // Min Heap representation     PriorityQueue<Integer> pq;    pq = new PriorityQueue<>();Â
    // Add all elements to heap     for(int i = 1; i <= N; i++)     {       pq.add(i);    }Â
    int cost = 0;Â
    while (pq.size() > 1)    {                 // First minimum         int mini = pq.remove();             // Second minimum         int secondmini = pq.remove();             // Multiply them         int current = mini * secondmini;             // Add to the cost         cost += current;             // Push the product into the         // heap again         pq.add(current);    }         // Return the optimal cost     return cost;}Â
// Driver Codepublic static void main(String args[]){Â Â Â Â int N = 5;Â
    // Function call     System.out.println(GetMinCost(N));}}Â
// This code is contributed by rutvik_56 |
Python3
# python3 program to find the Minimum # cost to merge numbers # from 1 to N.Â
# Function returns the # minimum costdef GetMinCost(N):         # Min Heap representation    pq = []Â
    # Add all elements to heap    for i in range(1, N+1, 1):        pq.append(i)Â
    pq.sort(reverse = False)         cost = 0         while (len(pq) > 1):                 # First minimum        mini = pq[0]        pq.remove(pq[0])Â
        # Second minimum        secondmini = pq[0]        pq.remove(pq[0])Â
        # Multiply them        current = mini * secondminiÂ
        # Add to the cost        cost += currentÂ
        # Push the product into the        # heap again        pq.append(current)        pq.sort(reverse = False)Â
    # Return the optimal cost    return costÂ
# Driver codeif __name__ == '__main__':Â Â Â Â Â Â Â Â Â N = 5Â Â Â Â print(GetMinCost(N))Â
# This code is contributed by Bhupendra_Singh |
C#
// C# program to find the Minimum // cost to merge numbers // from 1 to N. using System;using System.Collections.Generic;Â
class GFG{Â
// Function returns the // minimum cost static int GetMinCost(int N) {          // Min Heap representation     List<int> pq = new List<int>();        // Add all elements to heap     for(int i = 1; i <= N; i++)     {        pq.Add(i);     }            int cost = 0;     pq.Sort();         while (pq.Count > 1)     {                  // First minimum         int mini = pq[0];         pq.RemoveAt(0);            // Second minimum         int secondmini = pq[0];         pq.RemoveAt(0);           // Multiply them         int current = mini * secondmini;            // Add to the cost         cost += current;            // Push the product into the         // heap again         pq.Add(current);         pq.Sort();    }          // Return the optimal cost     return cost; } Â
// Driver codestatic void Main(){Â Â Â Â int N = 5;Â Â Â Â Â Â Â Â Â Console.WriteLine(GetMinCost(N));}}Â
// This code is contributed by divyeshrabadiya07 |
Javascript
<script>    // Javascript program for the above approach         // Function returns the    // minimum cost    function GetMinCost(N)    {Â
        // Min Heap representation        let pq = [];Â
        // Add all elements to heap        for(let i = 1; i <= N; i++)        {           pq.push(i);        }        pq.sort(function(a, b){return a - b});Â
        let cost = 0;Â
        while (pq.length > 1)        {Â
            // First minimum            let mini = pq[0];            pq.shift();Â
            // Second minimum            let secondmini = pq[0];            pq.shift();Â
            // Multiply them            let current = mini * secondmini;Â
            // Add to the cost            cost += current;Â
            // Push the product into the            // heap again            pq.push(current);            pq.sort(function(a, b){return a - b});        }Â
        // Return the optimal cost        return cost;    }         let N = 5;      // Function call    document.write(GetMinCost(N));     // This code is contributed by decode2207.</script> |
Output:Â
148
Â
Time Complexity: O(NlogN)Â
Auxiliary Space: O(N)
Â
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



