Minimum cost to partition the given binary string
Given a binary string str and an integer K, the task is to find the minimum cost required to partition the string into exactly K segments when the cost of each segment is the product of the number of set bits with the number of unset bits and total cost is sum of cost of all the individual segments.
Input: str = “110101”, K = 3
11|0|101 is one of the possible partitions
where the cost is 0 + 0 + 2 = 2
Input: str = “1000000”, K = 5
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.
Approach: Write a function minCost(s, k, cost, i, n) where cost is the minimum cost so far, i is the starting index for the partition and k is the remaining segments to be partitioned. Now, starting from the ith index calculate the cost of the current partition and call the same function recursively for the remaining substring. To memoize the result, a dp array will be used where dp[i][j] will store the minimum cost of partitioning the string into j parts starting at the ith index.
Below is the implementation of the above approach: