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
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read