Given an array a[] consisting of N integers and an integer K, the task is to find the minimum cost to reduce the given array to a single element by choosing any pair of consecutive array elements and replace them by (a[i] + a[i+1]) for a cost K * (a[i] + a[i+1]).
Examples:
Input: a[] = {1, 2, 3}, K = 2Â
Output: 18Â
Explanation:Â
Replacing {1, 2} by 3 modifies the array to {3, 3}. Cost 2 * 3 = 6Â
Replacing {3, 3} by 6 modifies the array to {6}. Cost 2 * 6 = 12Â
Therefore, the total cost is 18
Input: a[] = {4, 5, 6, 7}, K = 3Â
Output: 132
Naive Approach:Â
The simplest solution is to split the array into two halves, for every index and compute the cost of the two halves recursively and finally add their respective costs.
Below is the implementation of the above approach:
Â
C++
// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std;#define inf 10000009Â
// Function to combine the sum of the two halvesint Combine(int a[], int i, int j){Â Â Â Â int sum = 0;Â
    // Calculate the sum from i to j    for (int l = i; l <= j; l++)        sum += a[l];Â
    return sum;}Â
// Function to minimize the cost to// reduce the array to a single elementint minCost(int a[], int i, int j, int k){Â Â Â Â if (i >= j) Â Â Â Â {Â
        // Base case        // If n = 1 or n = 0        return 0;    }Â
    // Initialize cost to maximum value    int best_cost = inf;Â
    // Iterate through all possible indices    // and find the best index    // to combine the subproblems    for (int pos = i; pos < j; pos++)    {Â
        // Compute left subproblem        int left = minCost(a, i, pos, k);Â
        // Compute right subproblem        int right = minCost(a, pos + 1, j, k);Â
        // Calculate the best cost        best_cost = min(best_cost, left + right +                                    k * Combine(a, i, j));    }Â
    // Return the answer    return best_cost;}Â
// Driver codeint main(){Â Â Â Â int n = 4;Â Â Â Â int a[] = { 4, 5, 6, 7 };Â Â Â Â int k = 3;Â
    cout << minCost(a, 0, n - 1, k) << endl;    return 0;}Â
// This code is contributed by PrinciRaj1992 |
Java
// Java Program to implement// the above approachimport java.io.*;Â
class GFG {Â
    static int inf = 10000009;Â
    // Function to minimize the cost to    // reduce the array to a single element    public static int minCost(int a[], int i,                              int j, int k)    {        if (i >= j) {Â
            // Base case            // If n = 1 or n = 0            return 0;        }Â
        // Initialize cost to maximum value        int best_cost = inf;Â
        // Iterate through all possible indices        // and find the best index        // to combine the subproblems        for (int pos = i; pos < j; pos++) {Â
            // Compute left subproblem            int left = minCost(a, i, pos, k);Â
            // Compute right subproblem            int right = minCost(a, pos + 1, j, k);Â
            // Calculate the best cost            best_cost = Math.min(                best_cost,                left + right + k * Combine(a, i, j));        }Â
        // Return the answer        return best_cost;    }Â
    // Function to combine the sum of the two halves    public static int Combine(int a[], int i, int j)    {        int sum = 0;Â
        // Calculate the sum from i to j        for (int l = i; l <= j; l++)            sum += a[l];Â
        return sum;    }Â
    // Driver code    public static void main(String[] args)    {        int n = 4;        int a[] = { 4, 5, 6, 7 };        int k = 3;Â
        System.out.println(minCost(a, 0, n - 1, k));    }} |
Python3
# Python3 Program to implement# the above approachinf = 10000009;Â
# Function to minimize the cost to# reduce the array to a single elementdef minCost(a, i, j, k):    if (i >= j):               # Base case        # If n = 1 or n = 0        return 0;Â
    # Initialize cost to maximum value    best_cost = inf;Â
    # Iterate through all possible indices    # and find the best index    # to combine the subproblems    for pos in range(i, j):               # Compute left subproblem        left = minCost(a, i, pos, k);Â
        # Compute right subproblem        right = minCost(a, pos + 1, j, k);Â
        # Calculate the best cost        best_cost = min(best_cost,                         left + right +                        k * Combine(a, i, j));Â
    # Return the answer    return best_cost;Â
# Function to combine # the sum of the two halvesdef Combine(a, i, j):Â Â Â Â sum = 0;Â
    # Calculate the sum from i to j    for l in range(i, j + 1):        sum += a[l];Â
    return sum;Â
# Driver codeif __name__ == '__main__':Â Â Â Â n = 4;Â Â Â Â a = [4, 5, 6, 7];Â Â Â Â k = 3;Â
    print(minCost(a, 0, n - 1, k));Â
# This code is contributed by Amit Katiyar |
C#
// C# Program to implement// the above approachusing System;class GFG{Â
  static int inf = 10000009;Â
  // Function to minimize the cost to  // reduce the array to a single element  public static int minCost(int []a, int i,                            int j, int k)  {    if (i >= j)     {Â
      // Base case      // If n = 1 or n = 0      return 0;    }Â
    // Initialize cost to maximum value    int best_cost = inf;Â
    // Iterate through all possible indices    // and find the best index    // to combine the subproblems    for (int pos = i; pos < j; pos++)    {Â
      // Compute left subproblem      int left = minCost(a, i, pos, k);Â
      // Compute right subproblem      int right = minCost(a, pos + 1, j, k);Â
      // Calculate the best cost      best_cost = Math.Min(best_cost,                           left + right +                            k * Combine(a, i, j));    }Â
    // Return the answer    return best_cost;  }Â
  // Function to combine the sum of the two halves  public static int Combine(int []a, int i, int j)  {    int sum = 0;Â
    // Calculate the sum from i to j    for (int l = i; l <= j; l++)      sum += a[l];Â
    return sum;  }Â
  // Driver code  public static void Main(String[] args)  {    int n = 4;    int []a = { 4, 5, 6, 7 };    int k = 3;Â
    Console.WriteLine(minCost(a, 0, n - 1, k));  }}Â
// This code is contributed by Rohit_ranjan |
Javascript
<script>Â
// JavaScript Program to implement// the above approachvar inf = 10000009;Â
// Function to combine the sum of the two halvesfunction Combine(a, i, j){Â Â Â Â var sum = 0;Â
    // Calculate the sum from i to j    for (var l = i; l <= j; l++)        sum += a[l];Â
    return sum;}Â
// Function to minimize the cost to// reduce the array to a single elementfunction minCost(a, i, j, k){Â Â Â Â if (i >= j) Â Â Â Â {Â
        // Base case        // If n = 1 or n = 0        return 0;    }Â
    // Initialize cost to maximum value    var best_cost = inf;Â
    // Iterate through all possible indices    // and find the best index    // to combine the subproblems    for (var pos = i; pos < j; pos++)    {Â
        // Compute left subproblem        var left = minCost(a, i, pos, k);Â
        // Compute right subproblem        var right = minCost(a, pos + 1, j, k);Â
        // Calculate the best cost        best_cost = Math.min(best_cost, left + right +                                    k * Combine(a, i, j));    }Â
    // Return the answer    return best_cost;}Â
// Driver codeÂ
var n = 4;var a = [4, 5, 6, 7];var k = 3;document.write( minCost(a, 0, n - 1, k));Â
Â
</script> |
132
Â
Time Complexity: O(2N)Â
Auxiliary Space: O(1)
Â
Efficient Approach: To optimize the above approach, the idea is to use the concept of Dynamic Programming. Follow the steps below to solve the problem:
- Initialize a matrix dp[][] and such that dp[i][j] stores the sum from index i to j.
- Calculate sum(i, j) using Prefix Sum technique.
- Compute the sum of the two subproblems and update the cost with the minimum value.
- Store in dp[][] and return.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h>using namespace std;Â
int inf = 10000000; Â
// Function to generate the cost using // Prefix Sum Array technique vector<int> preprocess(vector<int> a, int n) { Â Â Â Â vector<int> p(n); Â Â Â Â p[0] = a[0]; Â Â Â Â Â Â Â Â Â for(int i = 1; i < n; i++) Â Â Â Â {Â Â Â Â Â Â Â Â p[i] = p[i - 1] + a[i]; Â Â Â Â }Â Â Â Â return p; }Â
// Function to combine the sum of the// two subproblems int Combine(vector<int> p, int i, int j) {     if (i == 0)         return p[j];     else        return p[j] - p[i - 1]; } Â
// Function to minimize the cost to // add the array elements to a single element int minCost(vector<int> a, int i, int j, int k, Â Â Â Â Â Â Â Â Â Â Â Â vector<int> prefix, vector<vector<int>> dp) { Â Â Â Â if (i >= j) Â Â Â Â Â Â Â Â return 0; Â
    // Check if the value is     // already stored in the array     if (dp[i][j] != -1)         return dp[i][j]; Â
    int best_cost = inf;     for(int pos = i; pos < j; pos++)    {                  // Compute left subproblem         int left = minCost(a, i, pos,                            k, prefix, dp); Â
        // Compute left subproblem         int right = minCost(a, pos + 1, j,                             k, prefix, dp); Â
        // Calculate minimum cost         best_cost = min(best_cost, left + right +                       (k * Combine(prefix, i, j)));     }          // Store the answer to     // avoid recalculation     return dp[i][j] = best_cost; } Â
// Driver code   int main(){    int n = 4; Â
    vector<int> a = { 4, 5, 6, 7 }; Â
    int k = 3; Â
    // Initialise dp array     vector<vector<int>> dp;    dp.resize(n + 1, vector<int>(n + 1));    for(int i = 0; i < n + 1; i++)    {        for(int j = 0; j < n + 1; j++)        {            dp[i][j] = -1;        }    }Â
    // Preprocessing the array     vector<int> prefix = preprocess(a, n);          cout << minCost(a, 0, n - 1, k, prefix, dp)         << endl;Â
    return 0;}Â
// This code is contributed by divyeshrabadiya07 |
Java
// Java Program for the above approachimport java.util.*;public class Main {Â
    static int inf = 10000000;Â
    // Function to minimize the cost to    // add the array elements to a single element    public static int minCost(int a[], int i, int j, int k,                              int[] prefix, int[][] dp)    {        if (i >= j)            return 0;Â
        // Check if the value is        // already stored in the array        if (dp[i][j] != -1)            return dp[i][j];Â
        int best_cost = inf;        for (int pos = i; pos < j; pos++) {Â
            // Compute left subproblem            int left = minCost(a, i, pos, k, prefix, dp);Â
            // Compute left subproblem            int right                = minCost(a, pos + 1, j, k, prefix, dp);Â
            // Calculate minimum cost            best_cost = Math.min(                best_cost,                left + right + (k * Combine(prefix, i, j)));        }Â
        // Store the answer to        // avoid recalculation        return dp[i][j] = best_cost;    }Â
    // Function to generate the cost using    // Prefix Sum Array technique    public static int[] preprocess(int[] a, int n)    {        int p[] = new int[n];        p[0] = a[0];        for (int i = 1; i < n; i++)            p[i] = p[i - 1] + a[i];        return p;    }Â
    // Function to combine the sum of the two subproblems    public static int Combine(int[] p, int i, int j)    {        if (i == 0)            return p[j];        else            return p[j] - p[i - 1];    }Â
    // Driver Code    public static void main(String args[])    {        int n = 4;Â
        int a[] = { 4, 5, 6, 7 };Â
        int k = 3;Â
        // Initialise dp array        int dp[][] = new int[n + 1][n + 1];        for (int i[] : dp)            Arrays.fill(i, -1);Â
        // Preprocessing the array        int prefix[] = preprocess(a, n);Â
        System.out.println(            minCost(a, 0, n - 1, k, prefix, dp));    }} |
Python3
# Python3 program for the above approachinf = 10000000Â
# Function to minimize the cost to# add the array elements to a single elementdef minCost(a, i, j, k, prefix, dp):Â Â Â Â Â Â Â Â Â if (i >= j):Â Â Â Â Â Â Â Â return 0Â
    # Check if the value is    # already stored in the array    if (dp[i][j] != -1):        return dp[i][j]Â
    best_cost = inf    for pos in range(i, j):Â
        # Compute left subproblem        left = minCost(a, i, pos,                       k, prefix, dp)Â
        # Compute left subproblem        right = minCost(a, pos + 1, j,                         k, prefix, dp)Â
        # Calculate minimum cost        best_cost = min(best_cost,                        left + right +                          (k * Combine(prefix, i, j)))Â
    # Store the answer to    # avoid recalculation    dp[i][j] = best_cost         return dp[i][j]Â
# Function to generate the cost using# Prefix Sum Array techniquedef preprocess(a, n):         p = [0] * n    p[0] = a[0]         for i in range(1, n):        p[i] = p[i - 1] + a[i]             return pÂ
# Function to combine the sum# of the two subproblemsdef Combine(p, i, j):Â Â Â Â Â Â Â Â Â if (i == 0):Â Â Â Â Â Â Â Â return p[j]Â Â Â Â else:Â Â Â Â Â Â Â Â return p[j] - p[i - 1]Â
# Driver Codeif __name__ == "__main__":Â Â Â Â Â Â Â Â Â n = 4Â Â Â Â a = [ 4, 5, 6, 7 ]Â Â Â Â k = 3Â
    # Initialise dp array    dp = [[-1 for x in range (n + 1)]              for y in range (n + 1)]Â
    # Preprocessing the array    prefix = preprocess(a, n)Â
    print(minCost(a, 0, n - 1, k, prefix, dp))Â
# This code is contributed by chitranayal |
C#
// C# Program for the above approachusing System;class GFG{Â
  static int inf = 10000000;Â
  // Function to minimize the cost to  // add the array elements to a single element  public static int minCost(int []a, int i, int j, int k,                            int[] prefix, int[,] dp)  {    if (i >= j)      return 0;Â
    // Check if the value is    // already stored in the array    if (dp[i, j] != -1)      return dp[i, j];Â
    int best_cost = inf;    for (int pos = i; pos < j; pos++)     {Â
      // Compute left subproblem      int left = minCost(a, i, pos, k, prefix, dp);Â
      // Compute left subproblem      int right = minCost(a, pos + 1, j,                           k, prefix, dp);Â
      // Calculate minimum cost      best_cost = Math.Min(best_cost, left + right +                           (k * Combine(prefix, i, j)));    }Â
    // Store the answer to    // avoid recalculation    return dp[i, j] = best_cost;  }Â
  // Function to generate the cost using  // Prefix Sum Array technique  public static int[] preprocess(int[] a, int n)  {    int []p = new int[n];    p[0] = a[0];    for (int i = 1; i < n; i++)      p[i] = p[i - 1] + a[i];    return p;  }Â
  // Function to combine the sum of the two subproblems  public static int Combine(int[] p, int i, int j)  {    if (i == 0)      return p[j];    else      return p[j] - p[i - 1];  }Â
  // Driver Code  public static void Main(String []args)  {    int n = 4;Â
    int []a = { 4, 5, 6, 7 };Â
    int k = 3;Â
    // Initialise dp array    int [,]dp = new int[n + 1, n + 1];    for(int i = 0; i < n + 1; i++)    {      for (int j = 0; j < n + 1; j++)      {        dp[i, j] = -1;      }    }    // Preprocessing the array    int []prefix = preprocess(a, n);Â
    Console.WriteLine(minCost(a, 0, n - 1, k,                               prefix, dp));  }}Â
// This code is contributed by sapnasingh4991 |
Javascript
<script>Â
// JavaScript program for the above approach Â
var inf = 10000000; Â
// Function to generate the cost using // Prefix Sum Array technique function preprocess(a, n) { Â Â Â Â var p = Array(n); Â Â Â Â p[0] = a[0]; Â Â Â Â Â Â Â Â Â for(var i = 1; i < n; i++) Â Â Â Â {Â Â Â Â Â Â Â Â p[i] = p[i - 1] + a[i]; Â Â Â Â }Â Â Â Â return p; }Â
// Function to combine the sum of the// two subproblems function Combine(p, i, j) {     if (i == 0)         return p[j];     else        return p[j] - p[i - 1]; } Â
// Function to minimize the cost to // add the array elements to a single element function minCost(a, i, j, k, prefix, dp) { Â Â Â Â if (i >= j) Â Â Â Â Â Â Â Â return 0; Â
    // Check if the value is     // already stored in the array     if (dp[i][j] != -1)         return dp[i][j]; Â
    var best_cost = inf;     for(var pos = i; pos < j; pos++)    {                  // Compute left subproblem         var left = minCost(a, i, pos,                            k, prefix, dp); Â
        // Compute left subproblem         var right = minCost(a, pos + 1, j,                             k, prefix, dp); Â
        // Calculate minimum cost         best_cost = Math.min(best_cost, left + right +                       (k * Combine(prefix, i, j)));     }          // Store the answer to     // avoid recalculation     return dp[i][j] = best_cost; } Â
// Driver code   var n = 4; var a = [4, 5, 6, 7]; var k = 3; // Initialise dp array var dp = Array.from(Array(n+1), ()=>Array(n+1).fill(-1));Â
// Preprocessing the array var prefix = preprocess(a, n); Â
document.write( minCost(a, 0, n - 1, k, prefix, dp))Â
</script> |
132
Â
Time Complexity: O(N2)Â
Auxiliary Space: O(N2)
Another approach : Using DP Tabulation method ( Iterative approach )
In this approach we use Dp to store computation of subproblems and get the desired output without the help of recursion.
Steps to solve this problem :
- Create a table DP to store the solution of the subproblems .
- Initialize the table with base cases
- Now Iterate over subproblems to get the value of current problem form previous computation of subproblems stored in DP
- Return the final solution stored in dp[0][n-1].
Implementation :
C++
// C++ code for above approachÂ
#include <bits/stdc++.h>using namespace std;Â
int inf = 10000000;Â
// Function to generate the cost using// Prefix Sum Array techniquevector<int> preprocess(vector<int> a, int n){Â Â Â Â vector<int> p(n);Â Â Â Â p[0] = a[0];Â Â Â Â Â Â Â Â Â for(int i = 1; i < n; i++)Â Â Â Â {Â Â Â Â Â Â Â Â p[i] = p[i - 1] + a[i];Â Â Â Â }Â Â Â Â return p;}Â
// Function to combine the sum of the// two subproblemsint Combine(vector<int> p, int i, int j){    if (i == 0)        return p[j];    else        return p[j] - p[i - 1];}Â
// Function to minimize the cost to// add the array elements to a single elementint minCost(vector<int> a, int n, int k){    // Initialise dp array    vector<vector<int>> dp(n + 1, vector<int>(n + 1));         // Preprocessing the array    vector<int> prefix = preprocess(a, n);         // Base case    for(int i = 0; i < n; i++)    {        dp[i][i] = 0;    }         // DP tabulation    for(int len = 2; len <= n; len++)    {        for(int i = 0; i <= n - len; i++)        {            int j = i + len - 1;            dp[i][j] = inf;                         for(int pos = i; pos < j; pos++)            {                int left = dp[i][pos];                int right = dp[pos + 1][j];                int cost = k * Combine(prefix, i, j);                dp[i][j] = min(dp[i][j], left + right + cost);            }        }    }           // return answer    return dp[0][n - 1];}Â
// Driver codeint main(){Â Â Â Â int n = 4;Â
    vector<int> a = { 4, 5, 6, 7 };Â
    int k = 3;           // function call    cout << minCost(a, n, k) << endl;Â
    return 0;}Â
// this code is contributed by bhardwajji |
Java
import java.util.*;Â
public class Main {Â Â static int inf = 10000000;Â
  // Function to generate the cost using  // Prefix Sum Array technique  static List<Integer> preprocess(List<Integer> a, int n)  {    List<Integer> p = new ArrayList<>();    p.add(a.get(0));Â
    for (int i = 1; i < n; i++) {      p.add(p.get(i - 1) + a.get(i));    }    return p;  }Â
  // Function to combine the sum of the  // two subproblems  static int Combine(List<Integer> p, int i, int j)  {    if (i == 0)      return p.get(j);    else      return p.get(j) - p.get(i - 1);  }Â
  // Function to minimize the cost to  // add the array elements to a single element  static int minCost(List<Integer> a, int n, int k)  {    // Initialise dp array    int[][] dp = new int[n + 1][n + 1];Â
    // Preprocessing the array    List<Integer> prefix = preprocess(a, n);Â
    // Base case    for (int i = 0; i < n; i++) {      dp[i][i] = 0;    }Â
    // DP tabulation    for (int len = 2; len <= n; len++) {      for (int i = 0; i <= n - len; i++) {        int j = i + len - 1;        dp[i][j] = inf;Â
        for (int pos = i; pos < j; pos++) {          int left = dp[i][pos];          int right = dp[pos + 1][j];          int cost = k * Combine(prefix, i, j);          dp[i][j] = Math.min(            dp[i][j], left + right + cost);        }      }    }Â
    // return answer    return dp[0][n - 1];  }Â
  // Driver code  public static void main(String[] args)  {    int n = 4;    List<Integer> a      = new ArrayList<>(Arrays.asList(4, 5, 6, 7));    int k = 3;Â
    // function call    System.out.println(minCost(a, n, k));  }} |
Python3
# codeINF = 10000000Â
# Function to generate the cost using# Prefix Sum Array techniqueÂ
Â
def preprocess(a, n):    p = [0] * n    p[0] = a[0]Â
    for i in range(1, n):        p[i] = p[i - 1] + a[i]Â
    return pÂ
# Function to combine the sum of the# two subproblemsÂ
Â
def Combine(p, i, j):Â Â Â Â if i == 0:Â Â Â Â Â Â Â Â return p[j]Â Â Â Â else:Â Â Â Â Â Â Â Â return p[j] - p[i - 1]Â
# Function to minimize the cost to# add the array elements to a single elementÂ
Â
def minCost(a, n, k):    # Initialise dp array    dp = [[0] * (n + 1) for i in range(n + 1)]Â
    # Preprocessing the array    prefix = preprocess(a, n)Â
    # Base case    for i in range(n):        dp[i][i] = 0Â
    # DP tabulation    for length in range(2, n + 1):        for i in range(n - length + 1):            j = i + length - 1            dp[i][j] = INFÂ
            for pos in range(i, j):                left = dp[i][pos]                right = dp[pos + 1][j]                cost = k * Combine(prefix, i, j)                dp[i][j] = min(dp[i][j], left + right + cost)Â
    # return answer    return dp[0][n - 1]Â
Â
if __name__ == '__main__':Â Â Â Â n = 4Â Â Â Â a = [4, 5, 6, 7]Â Â Â Â k = 3Â
    # function call    print(minCost(a, n, k)) |
C#
using System;using System.Collections.Generic;Â
class Program{Â Â Â Â static int inf = 10000000;Â
    // Function to generate the cost using    // Prefix Sum Array technique    static List<int> preprocess(List<int> a, int n)    {        List<int> p = new List<int>();        p.Add(a[0]);Â
        for (int i = 1; i < n; i++)        {            p.Add(p[i - 1] + a[i]);        }        return p;    }Â
    // Function to combine the sum of the    // two subproblems    static int Combine(List<int> p, int i, int j)    {        if (i == 0)            return p[j];        else            return p[j] - p[i - 1];    }Â
    // Function to minimize the cost to    // add the array elements to a single element    static int minCost(List<int> a, int n, int k)    {        // Initialise dp array        int[,] dp = new int[n + 1, n + 1];Â
        // Preprocessing the array        List<int> prefix = preprocess(a, n);Â
        // Base case        for (int i = 0; i < n; i++)        {            dp[i, i] = 0;        }Â
        // DP tabulation        for (int len = 2; len <= n; len++)        {            for (int i = 0; i <= n - len; i++)            {                int j = i + len - 1;                dp[i, j] = inf;Â
                for (int pos = i; pos < j; pos++)                {                    int left = dp[i, pos];                    int right = dp[pos + 1, j];                    int cost = k * Combine(prefix, i, j);                    dp[i, j] = Math.Min(dp[i, j], left + right + cost);                }            }        }Â
        // return answer        return dp[0, n - 1];    }Â
    // Driver code    static void Main(string[] args)    {        int n = 4;        List<int> a = new List<int>() { 4, 5, 6, 7 };        int k = 3;Â
        // function call        Console.WriteLine(minCost(a, n, k));    }} |
Javascript
// JavaScript code for above approachconst inf = 10000000;Â
// Function to generate the cost using// Prefix Sum Array techniquefunction preprocess(a, n) {Â Â Â Â let p = [];Â Â Â Â p[0] = a[0];Â Â Â Â for (let i = 1; i < n; i++) {Â Â Â Â Â Â Â Â p[i] = p[i - 1] + a[i];Â Â Â Â }Â Â Â Â return p;}Â
// Function to combine the sum of the// two subproblemsfunction Combine(p, i, j) {    if (i == 0)        return p[j];    else        return p[j] - p[i - 1];}Â
// Function to minimize the cost to// add the array elements to a single elementfunction minCost(a, n, k) {    // Initialise dp array    let dp = new Array(n + 1).fill().map(() => new Array(n + 1).fill(0));    // Preprocessing the array    let prefix = preprocess(a, n);Â
    // Base case    for (let i = 0; i < n; i++) {        dp[i][i] = 0;    }Â
    // DP tabulation    for (let len = 2; len <= n; len++) {        for (let i = 0; i <= n - len; i++) {            let j = i + len - 1;            dp[i][j] = inf;Â
            for (let pos = i; pos < j; pos++) {                let left = dp[i][pos];                let right = dp[pos + 1][j];                let cost = k * Combine(prefix, i, j);                dp[i][j] = Math.min(dp[i][j], left + right + cost);            }        }    }Â
    // return answer    return dp[0][n - 1];}Â
// Driver codelet n = 4;let a = [4, 5, 6, 7];let k = 3;Â
// function callconsole.log(minCost(a, n, k));Â
// This code is contributed by user_dtewbxkn77n |
Output
132
Time Complexity: O(N^3)Â
Auxiliary Space: O(N^2)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
