The Wayback Machine - https://web.archive.org/web/20240722045456/https://www.geeksforgeeks.org/minimum-cost-to-partition-the-given-binary-string/
Open In App

Minimum cost to partition the given binary string

Last Updated : 01 Mar, 2022
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

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.
Examples: 
 

Input: str = “110101”, K = 3 
Output: 2 
11|0|101 is one of the possible partitions 
where the cost is 0 + 0 + 2 = 2
Input: str = “1000000”, K = 5 
Output: 0 
 

 

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: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
const int MAX = 1001;
 
// dp[i][j] will store the minimum cost
// of partitioning the string into j
// parts starting at the ith index
int dp[MAX][MAX];
 
// Recursive function to find
// the minimum cost required
int minCost(string& s, int k, int cost, int i, int& n)
{
 
    // If the state has been solved before
    if (dp[i][k] != -1)
        return dp[i][k];
 
    // If only 1 part is left then the
    // remaining part of the string will
    // be considered as that part
    if (k == 1) {
 
        // To store the count of 0s and the
        // total characters of the string
        int count_0 = 0, total = n - i;
 
        // Count the 0s
        while (i < n)
            if (s[i++] == '0')
                count_0++;
 
        // Memoize and return the updated cost
        dp[i][k] = cost + (count_0
                           * (total - count_0));
        return dp[i][k];
    }
 
    int curr_cost = INT_MAX;
    int count_0 = 0;
 
    // Check all the positions to
    // make the current partition
    for (int j = i; j < n - k + 1; j++) {
 
        // Count the numbers of 0s
        if (s[j] == '0')
            count_0++;
        int curr_part_length = j - i + 1;
 
        // Cost of partition is equal to
        // (no. of 0s) * (no. of 1s)
        int part_cost = (count_0
                         * (curr_part_length - count_0));
 
        // string, partitions, curr cost,
        // start index, length
        part_cost += minCost(s, k - 1, 0, j + 1, n);
 
        // Update the current cost
        curr_cost = min(curr_cost, part_cost);
    }
 
    // Memoize and return the updated cost
    dp[i][k] = (cost + curr_cost);
    return (cost + curr_cost);
}
 
// Driver code
int main()
{
    string s = "110101";
    int n = s.length();
    int k = 3;
 
    // Initialise the dp array
    for (int i = 0; i < MAX; i++) {
        for (int j = 0; j < MAX; j++)
            dp[i][j] = -1;
    }
 
    // string, partitions, curr cost,
    // start index, length
    cout << minCost(s, k, 0, 0, n);
 
    return 0;
}


Java




// Java implementation of the approach
 
class GFG {
     
    final static int MAX = 1001;
     
    // dp[i][j] will store the minimum cost
    // of partitioning the string into j
    // parts starting at the ith index
    static int dp[][] = new int [MAX][MAX];
     
    // Recursive function to find
    // the minimum cost required
    static int minCost(String s, int k, int cost, int i, int n)
    {
     
        // If the state has been solved before
        if (dp[i][k] != -1)
            return dp[i][k];
     
        // If only 1 part is left then the
        // remaining part of the string will
        // be considered as that part
        if (k == 1) {
     
            // To store the count of 0s and the
            // total characters of the string
            int count_0 = 0, total = n - i;
     
            // Count the 0s
            while (i < n)
                if (s.charAt(i++) == '0')
                    count_0++;
     
            // Memoize and return the updated cost
            dp[i][k] = cost + (count_0
                            * (total - count_0));
            return dp[i][k];
        }
     
        int curr_cost = Integer.MAX_VALUE;
        int count_0 = 0;
     
        // Check all the positions to
        // make the current partition
        for (int j = i; j < n - k + 1; j++) {
     
            // Count the numbers of 0s
            if (s.charAt(j) == '0')
                count_0++;
            int curr_part_length = j - i + 1;
     
            // Cost of partition is equal to
            // (no. of 0s) * (no. of 1s)
            int part_cost = (count_0
                            * (curr_part_length - count_0));
     
            // string, partitions, curr cost,
            // start index, length
            part_cost += minCost(s, k - 1, 0, j + 1, n);
     
            // Update the current cost
            curr_cost = Math.min(curr_cost, part_cost);
        }
     
        // Memoize and return the updated cost
        dp[i][k] = (cost + curr_cost);
        return (cost + curr_cost);
    }
     
    // Driver code
    public static void main (String[] args)
    {
        String s = "110101";
        int n = s.length();
        int k = 3;
     
        // Initialise the dp array
        for (int i = 0; i < MAX; i++) {
            for (int j = 0; j < MAX; j++)
                dp[i][j] = -1;
        }
     
        // string, partitions, curr cost,
        // start index, length
        System.out.println(minCost(s, k, 0, 0, n));
     
     
    }
}
 
// This code is contributed by AnkitRai01


Python 3




# Python 3 implementation of the approach
import sys
MAX = 1001
 
# dp[i][j] will store the minimum cost
# of partitioning the string into j
# parts starting at the ith index
dp = [[0 for i in range(MAX)]
         for j in range(MAX)]
 
# Recursive function to find
# the minimum cost required
def minCost(s, k, cost, i, n):
     
    # If the state has been solved before
    if (dp[i][k] != -1):
        return dp[i][k]
 
    # If only 1 part is left then the
    # remaining part of the string will
    # be considered as that part
    if (k == 1):
         
        # To store the count of 0s and the
        # total characters of the string
        count_0 = 0
        total = n - i
 
        # Count the 0s
        while (i < n):
            if (s[i] == '0'):
                count_0 += 1
            i += 1
 
        # Memoize and return the updated cost
        dp[i][k] = cost + (count_0 *
                          (total - count_0))
        return dp[i][k]
 
    curr_cost = sys.maxsize
    count_0 = 0
 
    # Check all the positions to
    # make the current partition
    for j in range(i, n - k + 1, 1):
         
        # Count the numbers of 0s
        if (s[j] == '0'):
            count_0 += 1
        curr_part_length = j - i + 1
 
        # Cost of partition is equal to
        # (no. of 0s) * (no. of 1s)
        part_cost = (count_0 *
                    (curr_part_length - count_0))
 
        # string, partitions, curr cost,
        # start index, length
        part_cost += minCost(s, k - 1, 0, j + 1, n)
 
        # Update the current cost
        curr_cost = min(curr_cost, part_cost)
 
    # Memoize and return the updated cost
    dp[i][k] = (cost + curr_cost)
    return (cost + curr_cost)
 
# Driver code
if __name__ == '__main__':
    s = "110101"
    n = len(s)
    k = 3
 
    # Initialise the dp array
    for i in range(MAX):
        for j in range(MAX):
            dp[i][j] = -1
 
    # string, partitions, curr cost,
    # start index, length
    print(minCost(s, k, 0, 0, n))
     
# This code is contributed by Surendra_Gangwar


C#




// C# implementation of the approach
 
using System;
using System.Collections.Generic;
 
class GFG
{
     
    readonly static int MAX = 1001;
     
    // dp[i,j] will store the minimum cost
    // of partitioning the string into j
    // parts starting at the ith index
    static int [,]dp = new int [MAX, MAX];
     
    // Recursive function to find
    // the minimum cost required
    static int minCost(String s, int k, int cost, int i, int n)
    {
     
        int count_0 = 0;
        // If the state has been solved before
        if (dp[i, k] != -1)
            return dp[i, k];
     
        // If only 1 part is left then the
        // remaining part of the string will
        // be considered as that part
        if (k == 1)
        {
     
            // To store the count of 0s and the
            // total characters of the string
             
            int total = n - i;
     
            // Count the 0s
            while (i < n)
                if (s[i++] == '0')
                    count_0++;
     
            // Memoize and return the updated cost
            dp[i, k] = cost + (count_0
                            * (total - count_0));
            return dp[i, k];
        }
     
        int curr_cost = int.MaxValue;
        count_0 = 0;
     
        // Check all the positions to
        // make the current partition
        for (int j = i; j < n - k + 1; j++)
        {
     
            // Count the numbers of 0s
            if (s[j] == '0')
                count_0++;
            int curr_partlength = j - i + 1;
     
            // Cost of partition is equal to
            // (no. of 0s) * (no. of 1s)
            int part_cost = (count_0
                            * (curr_partlength - count_0));
     
            // string, partitions, curr cost,
            // start index,.Length
            part_cost += minCost(s, k - 1, 0, j + 1, n);
     
            // Update the current cost
            curr_cost = Math.Min(curr_cost, part_cost);
        }
     
        // Memoize and return the updated cost
        dp[i, k] = (cost + curr_cost);
        return (cost + curr_cost);
    }
     
    // Driver code
    public static void Main (String[] args)
    {
        String s = "110101";
        int n = s.Length;
        int k = 3;
     
        // Initialise the dp array
        for (int i = 0; i < MAX; i++)
        {
            for (int j = 0; j < MAX; j++)
                dp[i, j] = -1;
        }
     
        // string, partitions, curr cost,
        // start index,.Length
        Console.WriteLine(minCost(s, k, 0, 0, n));
    }
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
    // Javascript implementation of the approach
     
    let MAX = 1001;
       
    // dp[i][j] will store the minimum cost
    // of partitioning the string into j
    // parts starting at the ith index
    let dp = new Array(MAX);
       
    // Recursive function to find
    // the minimum cost required
    function minCost(s, k, cost, i, n)
    {
       
        // If the state has been solved before
        if (dp[i][k] != -1)
            return dp[i][k];
       
        // If only 1 part is left then the
        // remaining part of the string will
        // be considered as that part
        if (k == 1) {
       
            // To store the count of 0s and the
            // total characters of the string
            let count_0 = 0, total = n - i;
       
            // Count the 0s
            while (i < n)
                if (s[i++] == '0')
                    count_0++;
       
            // Memoize and return the updated cost
            dp[i][k] = cost + (count_0
                            * (total - count_0));
            return dp[i][k];
        }
       
        let curr_cost = Number.MAX_VALUE;
        let count_0 = 0;
       
        // Check all the positions to
        // make the current partition
        for (let j = i; j < n - k + 1; j++) {
       
            // Count the numbers of 0s
            if (s[j] == '0')
                count_0++;
            let curr_part_length = j - i + 1;
       
            // Cost of partition is equal to
            // (no. of 0s) * (no. of 1s)
            let part_cost = (count_0 * (curr_part_length - count_0));
       
            // string, partitions, curr cost,
            // start index, length
            part_cost += minCost(s, k - 1, 0, j + 1, n);
       
            // Update the current cost
            curr_cost = Math.min(curr_cost, part_cost);
        }
       
        // Memoize and return the updated cost
        dp[i][k] = (cost + curr_cost);
        return (cost + curr_cost);
    }
     
    let s = "110101";
    let n = s.length;
    let k = 3;
 
    // Initialise the dp array
    for (let i = 0; i < MAX; i++) {
      dp[i] = new Array(MAX);
      for (let j = 0; j < MAX; j++)
        dp[i][j] = -1;
    }
 
    // string, partitions, curr cost,
    // start index, length
    document.write(minCost(s, k, 0, 0, n));
 
// This code is contributed by divyeshrabadiya07.
</script>


Output: 

2

 

Time Complexity: O((n – k) + (MAX * MAX))

Auxiliary Space: O(MAX * MAX)



Similar Reads

Minimum cost to complete given tasks if cost of 1, 7 and 30 days are given
Given a sorted array arr[] consisting of N positive integers such that arr[i] represent the days in which a worker will work and an array cost[] of size 3 representing the salary paid to the workers for 1 day, 7 days and 30 days respectively, the task is to find the minimum cost required to have a worker for all the given days in arr[]. Examples: I
15+ min read
Minimum cost to remove all 1s from given Binary String as per given conditions
Given a binary sequence of 1's and 0's. Our task is to remove all 1s from the sequence in minimum cost by below operations. Remove an element from the left end (i.e., remove s[0]) which costs 1 coin.Remove an element from the right end (i.e., remove s[s.length - 1]) which costs 1 coin.Remove an element from anywhere in the sequence which costs 2 co
7 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 with the cost equal to the sum of elements of the su
11 min read
Minimum Cost To set Digital Clock Timer with given movement and push cost
Given integers A, B and N. The task is to minimize the cost to set N seconds in a digital clock where time is represented in the following format: at most 99 minutes and 99 secondsat least 1 secondThe first two digits represent minutes and the last two minutes represent seconds.It prepends 0 if less than 4 digits are pressed to set time A is the co
14 min read
Minimum Cost using Dijkstra by Modifying Cost of an Edge
Given an undirected weighted graph of N nodes and M edges in the form of a tuple lets say {X, Y, Z} such that there is an edge with cost Z between X and Y. We are supposed to compute the minimum cost of traversal from node 1 to N. However, we can perform one operation before the traversal such that we can reduce the cost of any edge lets say, C to
15 min read
Find minimum number of non palindromic partition of Binary Array
Given a binary array A[] of length 2*N, the task is to find the minimum number of partitions that follow the below conditions: Each array element belongs to exactly one partitionNone of the partitioned subarrays is a palindrome Note: If there are multiple answers print anyone that satisfies the above conditions and if no such partition exists that
7 min read
Minimum toggles to partition a binary array so that it has first 0s then 1s
Given an array of n integers containing only 0 and 1. Find the minimum toggles (switch from 0 to 1 or vice-versa) required such the array become partitioned, i.e., it has first 0s than 1s. There should be at least one 0 in the beginning, and there can be zero or more 1s in the end. Input: arr[] = {1, 0, 1, 1, 0} Output: 2 Toggle the first and last
7 min read
Partition array into two subsets with minimum Bitwise XOR between their maximum and minimum
Given an array arr[] of size N, the task is to split the array into two subsets such that the Bitwise XOR between the maximum of the first subset and minimum of the second subset is minimum. Examples: Input: arr[] = {3, 1, 2, 6, 4} Output: 1 Explanation: Splitting the given array in two subsets {1, 3}, {2, 4, 6}. The maximum of the first subset is
5 min read
Count ways to partition a Binary String such that each substring contains exactly two 0s
Given binary string str, the task is to find the count of ways to partition the string such that each partitioned substring contains exactly two 0s. Examples: Input: str = "00100" Output: 2Explanation: Possible ways to partition the string such that each partition contains exactly two 0s are: { {"00", "100"}, {"001", "00"} }. Therefore, the require
6 min read
Minimize cost to empty given array where cost of removing an element is its absolute difference with Time instant
Given an array arr[] consisting of N integers, the task is to find the minimum cost to remove all elements from the array such that the cost of removing any element is the absolute difference between the current time instant T (initially 1) and the array element arr[i] i.e., abs(T - arr[i]) where T. Examples: Input: arr[] = {3, 6, 4, 2}Output: 0Exp
9 min read
three90RightbarBannerImg