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 repace 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:

_Repacing {1, 2} by 3 modifies the array to {3, 3}. Cost 2 * 3 = 6 _

_Repacing {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 _

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

**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:

  • Java
  • C#

// Java Program to implement

// the above approach

**import** 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``;

}

// Intialize 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));

}

}

Output:

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.

#arrays #dynamic programming #recursion #prefix-sum

Minimize Cost to reduce the Array to a single element by given operations - GeeksforGeeks
23.45 GEEK