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 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 |
6
Time Complexity: O(N3), where N is the size of the given array.
Auxiliary Space: O(N)
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.
Recommended Posts:
- Split a given array into K subarrays minimizing the difference between their maximum and minimum
- Split a binary string into K subsets minimizing sum of products of occurrences of 0 and 1
- Split array into K disjoint subarrays such that sum of each subarray is odd.
- Count ways to split array into two equal sum subarrays by replacing each array element to 0 once
- Split an Array to maximize subarrays having equal count of odd and even elements for a cost not exceeding K
- Split array into maximum subarrays such that every distinct element lies in a single subarray
- Minimizing array sum by applying XOR operation on all elements of the array
- Split array into two subarrays such that difference of their maximum is minimum
- Split array into minimum number of subarrays having GCD of its first and last element exceeding 1
- Split array into two subarrays such that difference of their sum is minimum
- Minimum index to split array into subarrays with co-prime products
- Count of ways to split an Array into three contiguous Subarrays having increasing Sum
- Count ways to split array into two subarrays with equal GCD
- Minimizing array sum by subtracting larger elements from smaller ones
- Split array to three subarrays such that sum of first and third subarray is equal and maximum
- Split an array into two equal Sum subarrays
- Check if an array can be split into subarrays with GCD exceeding K
- Split the string into minimum parts such that each part is in the another string
- Split Array into min number of subsets with difference between each pair greater than 1
- Split array into two subsequences having minimum count of pairs with sum equal to X
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

