Given an array arr[] of N numbers. We can merge two adjacent numbers into one and the cost of merging the two numbers is equal to the sum of the two values. The task is to find the total minimum cost of merging all the numbers.
Examples:
Input: arr[] = { 6, 4, 4, 6 }
Output: 40
Explanation:
Following is the optimal way of merging numbers to get the total minimum cost of merging of numbers:
1. Merge (6, 4), then array becomes, arr[] = {10, 4, 6} and cost = 10
2. Merge (4, 6), then array becomes, arr[] = {10, 10} and cost = 10
3. Merge (10, 10), then array becomes, arr[] = {20} and cost = 20
Hence the total cost is 10 + 10 + 20 = 40.
Input: arr[] = { 3, 2, 4, 1 }
Output: 20
Explanation:
Following is the optimal way of merging numbers to get the total minimum cost of merging of numbers:
1. Merge (3, 2), then array becomes, arr[] = {5, 4, 1} and cost = 5
2. Merge (4, 1), then array becomes, arr[] = {5, 5} and cost = 5
3. Merge (5, 5), then array becomes, arr[] = {10} and cost = 10
Hence the total cost is 5 + 5 + 10 = 20.
Approach: The problem can be solved using Dynamic Programming. Below are the steps:
- The idea is to merge 2 consecutive numbers into every possible index i and then solve recursively for left and right parts of index i.
- Add the result of merging two numbers in above steps and store the minimum of them.
- Since there are many subproblems that are repeating, hence we use memoization to store the values in a NxN matrix.
- The recurrence relation for the above problem statement is given as:
dp[i][j] = min(dp[i][j], (sum[i][j] + dp[i][k] + dp[k + 1][j])), for every (i ? k lt; j)
5. Now dp[1][N] will give the minimum total cost of merging all the numbers.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;// Function to find the total minimum// cost of merging two consecutive numbersint mergeTwoNumbers(vector<int>& numbers){ int len, i, j, k; // Find the size of numbers[] int n = numbers.size(); // If array is empty, return 0 if (numbers.size() == 0) { return 0; } // To store the prefix Sum of // numbers array numbers[] vector<int> prefixSum(n + 1, 0); // Traverse numbers[] to find the // prefix sum for (int i = 1; i <= n; i++) { prefixSum[i] = prefixSum[i - 1] + numbers[i - 1]; } // dp table to memoised the value vector<vector<int> > dp( n + 1, vector<int>(n + 1)); // For single numbers cost is zero for (int i = 1; i <= n; i++) { dp[i][i] = 0; } // Iterate for length >= 1 for (len = 2; len <= n; len++) { for (i = 1; i <= n - len + 1; i++) { j = i + len - 1; // Find sum in range [i..j] int sum = prefixSum[j] - prefixSum[i - 1]; // Initialise dp[i][j] to INT_MAX dp[i][j] = INT_MAX; // Iterate for all possible // K to find the minimum cost for (k = i; k < j; k++) { // Update the minimum sum dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j] + sum); } } } // Return the final minimum cost return dp[1][n];}// Driver Codeint main(){ // Given set of numbers vector<int> arr1 = { 6, 4, 4, 6 }; // Function Call cout << mergeTwoNumbers(arr1) << endl; return 0;} |
Java
// Java program for the above approachimport java.util.*;class GFG{// Function to find the total minimum// cost of merging two consecutive numbersstatic int mergeTwoNumbers(int []numbers){ int len, i, j, k; // Find the size of numbers[] int n = numbers.length; // If array is empty, return 0 if (numbers.length == 0) { return 0; } // To store the prefix Sum of // numbers array numbers[] int []prefixSum = new int[n + 1]; // Traverse numbers[] to find the // prefix sum for (i = 1; i <= n; i++) { prefixSum[i] = prefixSum[i - 1] + numbers[i - 1]; } // dp table to memoised the value int [][]dp = new int[n + 1][n + 1]; // Iterate for length >= 1 for (len = 2; len <= n; len++) { for (i = 1; i <= n - len + 1; i++) { j = i + len - 1; // Find sum in range [i..j] int sum = prefixSum[j] - prefixSum[i - 1]; // Initialise dp[i][j] to Integer.MAX_VALUE dp[i][j] = Integer.MAX_VALUE; // Iterate for all possible // K to find the minimum cost for (k = i; k < j; k++) { // Update the minimum sum dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k + 1][j] + sum); } } } // Return the final minimum cost return dp[1][n];}// Driver Codepublic static void main(String[] args){ // Given set of numbers int []arr1 = { 6, 4, 4, 6 }; // Function Call System.out.print(mergeTwoNumbers(arr1) + "\n");}}// This code is contributed by sapnasingh4991 |
C#
// C# program for the above approach using System;class GFG{ // Function to find the total minimum // cost of merging two consecutive numbers static int mergeTwoNumbers(int []numbers) { int len, i, j, k; // Find the size of numbers[] int n = numbers.Length; // If array is empty, return 0 if (numbers.Length == 0) { return 0; } // To store the prefix Sum of // numbers array numbers[] int []prefixSum = new int[n + 1]; // Traverse numbers[] to find the // prefix sum for (i = 1; i <= n; i++) { prefixSum[i] = prefixSum[i - 1] + numbers[i - 1]; } // dp table to memoised the value int [,]dp = new int[n + 1, n + 1]; // Iterate for length >= 1 for (len = 2; len <= n; len++) { for (i = 1; i <= n - len + 1; i++) { j = i + len - 1; // Find sum in range [i..j] int sum = prefixSum[j] - prefixSum[i - 1]; // Initialise dp[i,j] to int.MaxValue dp[i,j] = int.MaxValue; // Iterate for all possible // K to find the minimum cost for (k = i; k < j; k++) { // Update the minimum sum dp[i, j] = Math.Min(dp[i, j], dp[i, k] + dp[k + 1, j] + sum); } } } // Return the readonly minimum cost return dp[1, n]; } // Driver Code public static void Main(String[] args) { // Given set of numbers int []arr1 = { 6, 4, 4, 6 }; // Function Call Console.Write(mergeTwoNumbers(arr1) + "\n"); } } // This code is contributed by sapnasingh4991 |
40
Time Complexity: O(N3)
Auxiliary Space Complexity: O(N2)
Recommended Posts:
- Maximize the cost of reducing array elements
- Minimize the cost to make all the adjacent elements distinct in an Array
- Minimum difference between adjacent elements of array which contain elements from each row of a matrix
- Minimum cost to make all array elements equal
- Minimum cost to equal all elements of array using two operation
- Make all array elements equal with minimum cost
- Make array elements equal with minimum cost
- Minimum Cost to make all array elements equal using given operations
- Minimum cost of choosing 3 increasing elements in an array of size N
- Minimum absolute difference of adjacent elements in a circular array
- Minimum elements to be inserted in Array to make adjacent differences equal
- Minimum operations required to modify the array such that parity of adjacent elements is different
- Missing occurrences of a number in an array such that maximum absolute difference of adjacent elements is minimum
- Minimum cost to empty Array where cost of removing an element is 2^(removed_count) * arr[i]
- Cost of creating smallest subsequence with sum of difference between adjacent elements maximum
- Maximum value after merging all elements in the array
- Merging elements of two different arrays alternatively in third array
- Modify array by merging elements with addition such that it consists of only Primes.
- Minimum elements to be removed such that sum of adjacent elements is always even
- Minimum elements to be removed such that sum of adjacent elements is always odd
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.
Improved By : sapnasingh4991


