Split array into subarrays at minimum cost by minimizing count of repeating elements in each subarray
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:
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
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>
Time Complexity: O(N3), where N is the size of the given array.
Auxiliary Space: O(N)
Similar Reads
Count ways to split array into two equal sum subarrays by replacing each array element to 0 once Given an array arr[] consisting of N integers, the task is to count the number of ways to split the array into two subarrays of equal sum after changing a single array element to 0. Examples: Input: arr[] = {1, 2, -1, 3}Output: 4Explanation: Replacing arr[0] by 0, arr[] is modified to {0, 2, -1, 3}.
11 min read
Split array into maximum subarrays such that every distinct element lies in a single subarray Given an array, arr[] of size N, the task is to split the array into the maximum number of subarrays such that the first and the last occurrence of all distinct array element lies in a single subarray. Examples: Input: arr[] = {1, 1, 2, 2}Output: 2Explanation:Split the array into subarrays {1, 1} an
6 min read
Minimize cost by splitting given Array into subsets of size K and adding highest K/2 elements of each subset into cost Given an array arr[] of N integers and an integer K, the task is to calculate the minimum cost by spilling the array elements into subsets of size K and adding the maximum âK/2â elements into the cost. Note: âK/2â means ceiling value of K/2. Examples: Input: arr[] = {1, 1, 2, 2}, K = 2Output: 3Expla
5 min read
Maximize the minimum array element by M subarray increments of size S Given an array arr[] of N integers and two integers S and M, the task is to maximize the minimum array element by incrementing any subarray of size S by 1, M number of times. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6}, S = 2, M = 3Output: 3Explanation:Below are the operations performed:Operation 1:
10 min read
Minimum cost to convert all elements of a K-size subarray to 0 from given Ternary Array with subarray sum as cost Given an array arr[] of N integers, where each array element is either 0, 1, or 2, and an integer K, the task is to print the minimum cost needed to convert all the elements of the array to 0s by selecting a subarray of size K and converting any array element of the subarray to 0 in one operation wi
11 min read