Minimum cost of reducing Array by merging any adjacent elements repetitively

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 |
Python3
# Python3 program for the above approachimport sys# Function to find the total minimum# cost of merging two consecutive numbersdef mergeTwoNumbers(numbers): # Find the size of numbers[] n = len(numbers) # If array is empty, return 0 if (len(numbers) == 0): return 0 # To store the prefix Sum of # numbers array numbers[] prefixSum = [0] * (n + 1) # Traverse numbers[] to find the # prefix sum for i in range(1, n + 1): prefixSum[i] = (prefixSum[i - 1] + numbers[i - 1]) # dp table to memoised the value dp = [[0 for i in range(n + 1)] for j in range(n + 1)] # For single numbers cost is zero for i in range(1, n + 1): dp[i][i] = 0 # Iterate for length >= 1 for p in range(2, n + 1): for i in range(1, n - p + 2): j = i + p - 1 # Find sum in range [i..j] sum = prefixSum[j] - prefixSum[i - 1] # Initialise dp[i][j] to _MAX dp[i][j] = sys.maxsize # Iterate for all possible # K to find the minimum cost for k in range(i, j): # 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 Code# Given set of numbersarr1 = [ 6, 4, 4, 6 ]# Function callprint(mergeTwoNumbers(arr1))# This code is contributed by sanjoy_62 |
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 |
Javascript
<script>// JavaScript program for the above approach// Function to find the total minimum// cost of merging two consecutive numbersfunction mergeTwoNumbers(numbers){ var len, i, j, k; // Find the size of numbers[] var n = numbers.length; // If array is empty, return 0 if (numbers.length == 0) { return 0; } // To store the prefix Sum of // numbers array numbers[] var prefixSum = Array(n+1).fill(0); // Traverse numbers[] to find the // prefix sum for (var i = 1; i <= n; i++) { prefixSum[i] = prefixSum[i - 1] + numbers[i - 1]; } // dp table to memoised the value var dp = Array.from(Array(n+1), ()=>Array(n+1)); // For single numbers cost is zero for (var 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] var sum = prefixSum[j] - prefixSum[i - 1]; // Initialise dp[i][j] to INT_MAX dp[i][j] = 1000000000; // 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 Code// Given set of numbersvar arr1 = [6, 4, 4, 6];// Function Calldocument.write( mergeTwoNumbers(arr1))</script> |
40
Time Complexity: O(N3)
Auxiliary Space Complexity: O(N2)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



