Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Split array into subarrays at minimum cost by minimizing count of repeating elements in each subarray

  • Difficulty Level : Expert
  • Last Updated : 06 Jun, 2021

Given an array arr[] having N integers from the range [1, N] and an integer K, the task is to find the minimum possible cost to split the array into non-empty subarrays that can be achieved based on the following conditions:

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: arr[] = {1, 2, 3, 1, 2, 3}, K = 2
Output: 4
Explanation: 
Splitting the array into subarrays {1, 2, 3} and {1, 2, 3} generates the minimum cost, as none of the subarrays contain any repeating element.
All other splits will cost higher as one subarray will contain at least one repeating element.
Therefore, the minimum possible cost is 4.



Input: arr[] = {1, 2, 1, 1, 1}, K = 2
Output: 6

Naive Approach: The simplest idea to solve the problem is to generate all possible subarrays to precompute and store their respective costs. Then, calculate the cost for every possible split that can be performed on the array. Finally, print the minimum cost from all the splits. 
Follow the steps below to solve the problem:

  1. Pre-compute the cost of every subarray based on the above conditions.
  2. Generate all possible split that can be performed on the array.
  3. For each split, calculate the total cost of every splitter subarray.
  4. Keep maintaining the minimum total cost generated and finally, print the minimum sum.

Time Complexity: O(N!)
Auxiliary Space: O(N)

Efficient Approach: The idea is to use Dynamic Programming to optimize the above approach. Follow the steps below to solve the problem:

  1. Initialize an array dp[] of length N with INT_MAX at all indices.
  2. Initialize the first element of the array with zero.
  3. For any index i the array dp[i] represents the minimum cost to divide the array into subarrays from 0 to i.
  4. For each index i, count the minimum cost for all the indices from i to N.
  5. Repeat this process for all the elements of the array
  6. Return the last elements of dp[] to get the minimum cost of splitting the array.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
#define ll long long
using namespace std;
 
// Function to find the minimum cost
// of splitting the array into subarrays
int findMinCost(vector<int>& a, int k)
{
    // Size of the array
    int n = (int)a.size();
 
    // Get the maximum element
    int max_ele = *max_element(a.begin(),
                               a.end());
 
    // dp[] will store the minimum cost
    // upto index i
    ll dp[n + 1];
 
    // Initialize the result array
    for (int i = 1; i <= n; ++i)
        dp[i] = INT_MAX;
 
    // Initialise the first element
    dp[0] = 0;
 
    for (int i = 0; i < n; ++i) {
 
        // Create the frequency array
        int freq[max_ele + 1];
 
        // Initialize frequency array
        memset(freq, 0, sizeof freq);
 
        for (int j = i; j < n; ++j) {
 
            // Update the frequency
            freq[a[j]]++;
            int cost = 0;
 
            // Counting the cost of
            // the duplicate element
            for (int x = 0;
                 x <= max_ele; ++x) {
                cost += (freq[x] == 1)
                            ? 0
                            : freq[x];
            }
 
            // Minimum cost of operation
            // from 0 to j
            dp[j + 1] = min(dp[i] + cost + k,
                            dp[j + 1]);
        }
    }
 
    // Total cost of the array
    return dp[n];
}
 
// Driver Code
int main()
{
    vector<int> arr = { 1, 2, 1, 1, 1 };
 
    // Given cost K
    int K = 2;
 
    // Function Call
    cout << findMinCost(arr, K);
 
    return 0;
}

Java




// Java program for the above approach
import java.util.*;
class GFG {
 
// Function to find the
// minimum cost of splitting
// the array into subarrays
static long findMinCost(int[] a,
                        int k, int n)
{
  // Get the maximum element
  int max_ele = Arrays.stream(a).max().getAsInt();
 
  // dp[] will store the minimum cost
  // upto index i
  long[] dp = new long[n + 1];
 
  // Initialize the result array
  for (int i = 1; i <= n; ++i)
    dp[i] = Integer.MAX_VALUE;
 
  // Initialise the first element
  dp[0] = 0;
 
  for (int i = 0; i < n; ++i)
  {
    // Create the frequency array
    int[] freq = new int[max_ele + 1];
 
    for (int j = i; j < n; ++j)
    {
      // Update the frequency
      freq[a[j]]++;
      int cost = 0;
 
      // Counting the cost of
      // the duplicate element
      for (int x = 0; x <= max_ele; ++x)
      {
        cost += (freq[x] == 1) ? 0 :
                 freq[x];
      }
 
      // Minimum cost of operation
      // from 0 to j
      dp[j + 1] = Math.min(dp[i] + cost + k,
                           dp[j + 1]);
    }
  }
 
  // Total cost of the array
  return dp[n];
}
 
// Driver Code
public static void main(String[] args)
{
  int[] arr = {1, 2, 1, 1, 1};
 
  // Given cost K
  int K = 2;
  int n = arr.length;
   
  // Function Call
  System.out.print(findMinCost(arr,
                               K, n));
}
}
 
// This code is contributed by gauravrajput1

Python3




# Python3 program for the above approach
import sys
 
# Function to find the
# minimum cost of splitting
# the array into subarrays
def findMinCost(a, k, n):
     
    # Get the maximum element
    max_ele = max(a)
 
    # dp will store the minimum cost
    # upto index i
    dp = [0] * (n + 1)
 
    # Initialize the result array
    for i in range(1, n + 1):
        dp[i] = sys.maxsize
 
    # Initialise the first element
    dp[0] = 0
 
    for i in range(0, n):
         
        # Create the frequency array
        freq = [0] * (max_ele + 1)
 
        for j in range(i, n):
             
            # Update the frequency
            freq[a[j]] += 1
            cost = 0
 
            # Counting the cost of
            # the duplicate element
            for x in range(0, max_ele + 1):
                cost += (0 if (freq[x] == 1) else
                               freq[x])
 
            # Minimum cost of operation
            # from 0 to j
            dp[j + 1] = min(dp[i] + cost + k,
                            dp[j + 1])
 
    # Total cost of the array
    return dp[n]
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 1, 2, 1, 1, 1 ];
 
    # Given cost K
    K = 2;
    n = len(arr);
 
    # Function call
    print(findMinCost(arr, K, n));
 
# This code is contributed by Amit Katiyar

C#




// C# program for the above approach
using System;
using System.Linq;
class GFG{
 
// Function to find the
// minimum cost of splitting
// the array into subarrays
static long findMinCost(int[] a,
                        int k, int n)
{
  // Get the maximum element
  int max_ele = a.Max();
 
  // []dp will store the minimum cost
  // upto index i
  long[] dp = new long[n + 1];
 
  // Initialize the result array
  for (int i = 1; i <= n; ++i)
    dp[i] = int.MaxValue;
 
  // Initialise the first element
  dp[0] = 0;
 
  for (int i = 0; i < n; ++i)
  {
    // Create the frequency array
    int[] freq = new int[max_ele + 1];
 
    for (int j = i; j < n; ++j)
    {
      // Update the frequency
      freq[a[j]]++;
      int cost = 0;
 
      // Counting the cost of
      // the duplicate element
      for (int x = 0; x <= max_ele; ++x)
      {
        cost += (freq[x] == 1) ? 0 :
                 freq[x];
      }
 
      // Minimum cost of operation
      // from 0 to j
      dp[j + 1] = Math.Min(dp[i] + cost + k,
                           dp[j + 1]);
    }
  }
 
  // Total cost of the array
  return dp[n];
}
 
// Driver Code
public static void Main(String[] args)
{
  int[] arr = {1, 2, 1, 1, 1};
 
  // Given cost K
  int K = 2;
  int n = arr.Length;
   
  // Function Call
  Console.Write(findMinCost(arr,
                               K, n));
}
}
 
// This code is contributed by shikhasingrajput

Javascript




<script>
 
// Javascript program for the above approach
 
// Function to find the minimum cost
// of splitting the array into subarrays
function findMinCost(a, k)
{
     
    // Size of the array
    var n = a.length;
 
    // Get the maximum element
    var max_ele = a.reduce((a, b) => Math.max(a, b))
 
    // dp[] will store the minimum cost
    // upto index i
    var dp = Array(n + 1).fill(1000000000);
 
    // Initialise the first element
    dp[0] = 0;
 
    for(var i = 0; i < n; ++i)
    {
         
        // Create the frequency array
        var freq = Array(max_ele + 1).fill(0);
 
        for(var j = i; j < n; ++j)
        {
             
            // Update the frequency
            freq[a[j]]++;
            var cost = 0;
 
            // Counting the cost of
            // the duplicate element
            for(var x = 0; x <= max_ele; ++x)
            {
                cost += (freq[x] == 1) ? 0 : freq[x];
            }
 
            // Minimum cost of operation
            // from 0 to j
            dp[j + 1] = Math.min(dp[i] + cost + k,
                                 dp[j + 1]);
        }
    }
 
    // Total cost of the array
    return dp[n];
}
 
// Driver Code
var arr = [ 1, 2, 1, 1, 1 ];
 
// Given cost K
var K = 2;
 
// Function Call
document.write(findMinCost(arr, K));
 
// This code is contributed by itsok
 
</script>
Output: 
6

Time Complexity: O(N3), where N is the size of the given array.
Auxiliary Space: O(N)




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!