Minimize Cost to reduce the Array to a single element by given operations

19 Jan, 2022
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 18Input: 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++
Java
Python3
C#
Javascript
// 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 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 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# 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
<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++
Java
Python3
C#
Javascript
// 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 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 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 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 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# 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
<script> // JavaScript program for the above approach var inf = 10000000; // Function to generate the cost using// Prefix Sum Array techniquefunction 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 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, 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 arrayvar dp = Array.from(Array(n+1), ()=>Array(n+1).fill(-1)); // Preprocessing the arrayvar prefix = preprocess(a, n); document.write( minCost(a, 0, n - 1, k, prefix, dp)) </script>
132
 
Time Complexity: O(N2) Auxiliary Space: O(N2)
Rohit_ranjan
princiraj1992
sapnasingh4991
amit143katiyar
ukasp
divyeshrabadiya07
rutvik_56
rrrtnx
khushboogoyal499
gabaa406
sumitgumber28
prefix-sum
Arrays
Dynamic Programming
Recursion
prefix-sum
Arrays
Dynamic Programming
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
0-1 Knapsack Problem | DP-10
Longest Common Subsequence | DP-4
Subset Sum Problem | DP-25
Longest Palindromic Substring | Set 1
Longest Increasing Subsequence | DP-3