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: 32Merging {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 = 152But 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 cost int 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 code int 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 Code public 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 cost def 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 code if __name__ == '__main__': N = 5 print(GetMinCost(N)) # This code is contributed by Bhupendra_Singh |
148
Time Complexity: O(NlogN)
Auxiliary Space: O(N)
Recommended Posts:
- Minimum cost to empty Array where cost of removing an element is 2^(removed_count) * arr[i]
- Minimum Cost using Dijkstra by reducing cost of an Edge
- Minimum Cost Graph
- Minimum cost to make two strings same
- Minimum possible travel cost among N cities
- Connect n ropes with minimum cost
- Minimum odd cost path in a matrix
- Merge K minimum elements of the array until there is only one element
- Minimum cost to partition the given binary string
- Minimum cost to traverse from one index to another in the String
- Minimum cost of choosing the array element
- Minimum cost to cover the given positions in a N*M grid
- Find the minimum cost to cross the River
- Minimum cost to buy N kilograms of sweet for M persons
- Minimum cost to make all array elements equal
- Minimum cost to reach a point N from 0 with two different operations allowed
- Minimum cost to reach the top of the floor by climbing stairs
- Choose atleast two elements from array such that their GCD is 1 and cost is minimum
- Minimum cost to form a number X by adding up powers of 2
- Minimum total cost incurred to reach the last station
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


