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:
- If no unique element is present in the subarray, the cost is K.
- Otherwise, the cost is K + Sum of frequencies of every repeating element.
Examples:
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:
- Pre-compute the cost of every subarray based on the above conditions.
- Generate all possible split that can be performed on the array.
- For each split, calculate the total cost of every splitter subarray.
- 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:
- Initialize an array dp[] of length N with INT_MAX at all indices.
- Initialize the first element of the array with zero.
- For any index i the array dp[i] represents the minimum cost to divide the array into subarrays from 0 to i.
- For each index i, count the minimum cost for all the indices from i to N.
- Repeat this process for all the elements of the array
- 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 longusing namespace std;Â
// Function to find the minimum cost// of splitting the array into subarraysint 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 Codeint 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 approachimport java.util.*;class GFG {Â
// Function to find the // minimum cost of splitting // the array into subarraysstatic 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 Codepublic 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 approachimport sysÂ
# Function to find the# minimum cost of splitting# the array into subarraysdef 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 Codeif __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 approachusing System;using System.Linq;class GFG{Â
// Function to find the // minimum cost of splitting // the array into subarraysstatic 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 Codepublic 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 subarraysfunction 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 Codevar arr = [ 1, 2, 1, 1, 1 ];Â
// Given cost Kvar K = 2;Â
// Function Calldocument.write(findMinCost(arr, K));Â
// This code is contributed by itsokÂ
</script> |
6
Time Complexity: O(N3), where N is the size of the given array.
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
