# Program to find out the cost to merge an array of integers into a single value in C++

C++Server Side ProgrammingProgramming

Suppose we are given an array arr that contains n positive integer numbers. We are also given an integer number j. The task we have to perform is to merge j numbers into a single number by adding them. The cost of merging is equal to the addition of the j numbers we have selected. We have to find out the minimum possible cost for this merging operation.

So, if the input is like arr = [2, 5, 6, 2, 3, 1, 3], j = 4, then the output will be 31.

Cost to merge 2, 3, 1, 3 is equal to 2 + 3 + 1 + 3 = 9.

The array after the merge operation becomes [2, 5, 6, 9]. The cost of the second merge operation is equal to 2 + 5 + 6 + 9 = 22. So, the total cost of the merge operation becomes 22 + 9 = 31. This is the minimum merging cost.

To solve this, we will follow these steps −

• n := size of arr
• if (n - 1) mod (j - 1) is not equal to 0, then −
• return -1
• Define an array temp(n + 1)
• for initialize i := n - 1, when i >= 0, update (decrease i by 1), do −
• temp[i] := arr[i] + temp[i + 1]
• Define one 2D array dynArr of order n x n
• for initialize k := j, when k <= n, update (increase k by 1), do −
• for initialize le := 0, rg := k - 1, when rg < n, update (increase le by 1), (increase rg by 1), do −
• dynArr[le, rg] := inf
• for initialize i := le, when i < rg, update i := i + j - 1, do −
• dynArr[le, rg] := minimum of (dynArr[le, rg] and dynArr[le, i] + dynArr[i + 1, rg])
• if (rg - le) mod (j - 1) is same as 0, then −
• dynArr[le, rg] := dynArr[le, rg] + temp[le] - temp[rg + 1]
• return dynArr[0, n - 1]

## Example

Let us see the following implementation to get better understanding −

#include<bits/stdc++.h>
using namespace std;
int solve(vector<int>& arr, int j) {
int n = arr.size();
if ((n - 1) % (j - 1) != 0) return -1;

vector<int> temp(n + 1);
for (int i = n - 1; i >= 0; i--) {
temp[i] = arr[i] + temp[i + 1];
}
vector<vector<int>> dynArr(n, vector<int>(n));
for (int k = j; k <= n; k++) {
for (int le = 0, rg = k - 1; rg < n; le++, rg++) {
dynArr[le][rg] = INT_MAX;
for (int i = le; i < rg; i += j - 1) {
dynArr[le][rg] = min(dynArr[le][rg], dynArr[le][i] + dynArr[i + 1][rg]);
}
if ((rg - le) % (j - 1) == 0) {
dynArr[le][rg] += temp[le] - temp[rg + 1];
}
}
}
return dynArr[n - 1];
}

int main() {
vector<int> arr = {2, 5, 6, 2, 3, 1, 3};
cout<< solve(arr, 4) <<endl;
return 0;
}

## Input

{2, 5, 6, 2, 3, 1, 3}, 4

## Output

31