Problem Description
Given an integer array A of size N. You have to merge all the elements of the array into one with the minimum possible cost.
The rule for merging is as follows:
Return the minimum possible cost of merging all elements.
Problem Constraints
1 <= N <= 200
1 <= A[i] <= 103
Input Format
First and only argument is an integer array A of size N.
Output Format
Return an integer denoting the minimum cost of merging all elements.
Example Input
Input 1:
A = [1, 3, 7]
Input 2:
A = [1, 2, 3, 4]
Example Output
Output 1:
15
Output 2:
19
Example Explanation
Explanation 1:
All possible ways of merging: a) {1, 3, 7} (cost = 0) -> {4, 7} (cost = 4) -> {11} (cost = 4+11 = 15) b) {1, 3, 7} (cost = 0) -> {1, 10} (cost = 10) -> {11} (cost = 10+11 = 21) Thus, ans = 15
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:
No comments:
Post a Comment
Please do not enter any spam link in the comment box