Open In App

Split a binary string into K subsets minimizing sum of products of occurrences of 0 and 1

Last Updated : 09 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a binary string S, the task is to partition the sequence into K non-empty subsets such that the sum of products of occurrences of 0 and 1 for all subsets is minimum. If impossible print -1.
Examples: 
 

Input: S = “0001”, K = 2 
Output:
Explanation 
We have 3 choices {0, 001}, {00, 01}, {000, 1} 
The respective sum of products are {1*0 + 2*1 = 2}, {2*0 + 1*1 = 1}, {3*0 + 0*1 = 0}.
Input: S = “1011000110110100”, K = 5 
Output:
Explanation: The subsets {10, 11, 000, 11011, 0100} minimizes the sum of product { 1*1 + 0*2 + 3*0 + 1*4 + 3*1 = 8 }. 
 

 

Approach: In order to solve this problem we are using bottom-up dynamic programming
 

  • We calculate the minimum sum of products for all subsets and then, for every subset we use this value to compute the minimum sum of products for all sizes of that subset.
  • For a subset starting at index i and ending at index j the value will be minimum of dp[i-1] + (count_zero * count_one) where count_zero and count_one are the occurrences of 0 and 1 between i and j respectively.
  • For each index j, we find the minimum value amongst all possible values of i.
  • Return dp[N – 1] for the final answer.

Below code is the implementation of the above approach: 
 

C++




// C++ Program to split a given string
// into K segments such that the sum
// of product of occurrence of
// characters in them is minimized
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the minimum
// sum of products of occurrences
// of 0 and 1 in each segments
int minSumProd(string S, int K)
{
    // Store the length of
    // the string
    int len = S.length();
 
    // Not possible to
    // generate subsets
    // greater than the
    // length of string
    if (K > len)
        return -1;
 
    // If the number of subsets
    // equals the length
    if (K == len)
        return 0;
 
    vector<int> dp(len);
    int count_zero = 0, count_one = 0;
 
    // Precompute the sum of
    // products for all index
    for (int j = 0; j < len; j++) {
 
        (S[j] == '0')
            ? count_zero++
            : count_one++;
        dp[j] = count_zero * count_one;
    }
 
    // Calculate the minimum sum of
    // products for K subsets
    for (int i = 1; i < K; i++) {
 
        for (int j = len; j >= i; j--) {
 
            count_zero = 0, count_one = 0;
            dp[j] = INT_MAX;
 
            for (int k = j; k >= i; k--) {
 
                (S[k] == '0') ? count_zero++
                              : count_one++;
                dp[j]
                    = min(
                        dp[j],
                        count_zero * count_one
                            + dp[k - 1]);
            }
        }
    }
 
    return dp[len - 1];
}
 
// Driver code
int main()
{
    string S = "1011000110110100";
    int K = 5;
    cout << minSumProd(S, K) << '\n';
    return 0;
}


Java




// Java Program to split a given String
// into K segments such that the sum
// of product of occurrence of
// characters in them is minimized
import java.util.*;
 
class GFG{
 
// Function to return the minimum
// sum of products of occurrences
// of 0 and 1 in each segments
static int minSumProd(String S, int K)
{
    // Store the length of
    // the String
    int len = S.length();
 
    // Not possible to
    // generate subsets
    // greater than the
    // length of String
    if (K > len)
        return -1;
 
    // If the number of subsets
    // equals the length
    if (K == len)
        return 0;
 
    int []dp = new int[len];
    int count_zero = 0, count_one = 0;
 
    // Precompute the sum of
    // products for all index
    for (int j = 0; j < len; j++)
    {
        if(S.charAt(j) == '0')
            count_zero++;
        else
            count_one++;
        dp[j] = count_zero * count_one;
    }
 
    // Calculate the minimum sum of
    // products for K subsets
    for (int i = 1; i < K; i++)
    {
        for (int j = len-1; j >= i; j--)
        {
            count_zero = 0;
            count_one = 0;
            dp[j] = Integer.MAX_VALUE;
 
            for (int k = j; k >= i; k--)
            {
                if(S.charAt(k) == '0')
                    count_zero++;
                else
                    count_one++;
                dp[j] = Math.min(dp[j], count_zero *
                                        count_one +
                                        dp[k - 1]);
            }
        }
    }
     
    return dp[len - 1];
}
 
// Driver code
public static void main(String[] args)
{
    String S = "1011000110110100";
    int K = 5;
    System.out.print(minSumProd(S, K));
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 program to split a given String
# into K segments such that the sum
# of product of occurrence of
# characters in them is minimized
import sys
 
# Function to return the minimum
# sum of products of occurrences
# of 0 and 1 in each segments
def minSumProd(S, K):
     
    # Store the length of
    # the String
    Len = len(S);
 
    # Not possible to
    # generate subsets
    # greater than the
    # length of String
    if (K > Len):
        return -1;
 
    # If the number of subsets
    # equals the length
    if (K == Len):
        return 0;
 
    dp = [0] * Len;
    count_zero = 0;
    count_one = 0;
 
    # Precompute the sum of
    # products for all index
    for j in range(0, Len, 1):
        if (S[j] == '0'):
            count_zero += 1;
        else:
            count_one += 1;
        dp[j] = count_zero * count_one;
 
    # Calculate the minimum sum of
    # products for K subsets
    for i in range(1, K):
        for j in range(Len - 1, i - 1, -1):
            count_zero = 0;
            count_one = 0;
            dp[j] = sys.maxsize;
 
            for k in range(j, i - 1, -1):
                if (S[k] == '0'):
                    count_zero += 1;
                else:
                    count_one += 1;
 
                dp[j] = min(dp[j], count_zero *
                                   count_one +
                                   dp[k - 1]);
    return dp[Len - 1];
 
# Driver code
if __name__ == '__main__':
 
    S = "1011000110110100";
    K = 5;
     
    print(minSumProd(S, K));
 
# This code is contributed by 29AjayKumar


C#




// C# program to split a given String
// into K segments such that the sum
// of product of occurrence of
// characters in them is minimized
using System;
 
class GFG{
 
// Function to return the minimum
// sum of products of occurrences
// of 0 and 1 in each segments
static int minSumProd(string S, int K)
{
     
    // Store the length of
    // the String
    int len = S.Length;
 
    // Not possible to
    // generate subsets
    // greater than the
    // length of String
    if (K > len)
        return -1;
 
    // If the number of subsets
    // equals the length
    if (K == len)
        return 0;
 
    int []dp = new int[len];
    int count_zero = 0, count_one = 0;
 
    // Precompute the sum of
    // products for all index
    for(int j = 0; j < len; j++)
    {
       if(S[j] == '0')
       {
           count_zero++;
       }
       else
       {
           count_one++;
       }
       dp[j] = count_zero * count_one;
    }
 
    // Calculate the minimum sum
    // of products for K subsets
    for(int i = 1; i < K; i++)
    {
       for(int j = len - 1; j >= i; j--)
       {
          count_zero = 0;
          count_one = 0;
          dp[j] = Int32.MaxValue;
           
          for(int k = j; k >= i; k--)
          {
             if(S[k] == '0')
             {
                 count_zero++;
             }
             else
             {
                 count_one++;
             }
             dp[j] = Math.Min(dp[j], count_zero *
                                      count_one +
                                      dp[k - 1]);
          }
       }
    }
    return dp[len - 1];
}
 
// Driver code
public static void Main(string[] args)
{
    string S = "1011000110110100";
    int K = 5;
     
    Console.Write(minSumProd(S, K));
}
}
 
// This code is contributed by rutvik_56


Javascript




<script>
// Javascript Program to split a given string
// into K segments such that the sum
// of product of occurrence of
// characters in them is minimized
 
 
// Function to return the minimum
// sum of products of occurrences
// of 0 and 1 in each segments
function minSumProd(S, K) {
    // Store the length of
    // the string
    let len = S.length;
 
    // Not possible to
    // generate subsets
    // greater than the
    // length of string
    if (K > len)
        return -1;
 
    // If the number of subsets
    // equals the length
    if (K == len)
        return 0;
 
    let dp = new Array(len);
    let count_zero = 0, count_one = 0;
 
    // Precompute the sum of
    // products for all index
    for (let j = 0; j < len; j++) {
 
        (S[j] == '0')
            ? count_zero++
            : count_one++;
        dp[j] = count_zero * count_one;
    }
 
    // Calculate the minimum sum of
    // products for K subsets
    for (let i = 1; i < K; i++) {
 
        for (let j = len; j >= i; j--) {
 
            count_zero = 0, count_one = 0;
            dp[j] = Number.MAX_SAFE_INTEGER;
 
            for (let k = j; k >= i; k--) {
 
                (S[k] == '0') ? count_zero++
                    : count_one++;
                dp[j]
                    = Math.min(
                        dp[j],
                        count_zero * count_one
                        + dp[k - 1]);
            }
        }
    }
 
    return dp[len - 1];
}
 
// Driver code
let S = "1011000110110100";
let K = 5;
document.write(minSumProd(S, K));
 
// This code is contributed by _saurabh_jaiswal
</script>


Output: 

8

 

Time Complexity: O(K*N*N) 
Auxiliary Space Complexity: O(N)
 



Similar Reads

Split array into minimum number of subsets such that elements of all pairs are present in different subsets at least once
Given an array arr[] consisting of N distinct integers, the task is to find the minimum number of times the array needs to be split into two subsets such that elements of each pair are present into two different subsets at least once. Examples: Input: arr[] = { 3, 4, 2, 1, 5 } Output: 3 Explanation: Possible pairs are { (1, 2), (1, 3), (1, 4), (1,
6 min read
Maximum number of subsets an array can be split into such that product of their minimums with size of subsets is at least K
Given an array arr[] consisting of N integers and an integer K, the task is to find the maximum number of disjoint subsets that the given array can be split into such that the product of the minimum element of each subset with the size of the subset is at least K. Examples: Input: arr[] = {7, 11, 2, 9, 5}, K = 10Output: 2Explanation:All such disjoi
8 min read
Split a given array into K subarrays minimizing the difference between their maximum and minimum
Given a sorted array arr[] of N integers and an integer K, the task is to split the array into K subarrays such that the sum of the difference of maximum and minimum element of each subarray is minimized. Examples: Input: arr[] = {1, 3, 3, 7}, K = 4 Output: 0 Explanation: The given array can be split into 4 subarrays as {1}, {3}, {3}, and {7}. The
6 min read
Split array into subarrays at minimum cost by minimizing count of repeating elements in each subarray
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 repeati
8 min read
Minimum length of a rod that can be split into N equal parts that can further be split into given number of equal parts
Given an array arr[] consisting of N positive integers, the task is to find the minimum possible length of a rod that can be cut into N equal parts such that every ith part can be cut into arr[i] equal parts. Examples: Input: arr[] = {1, 2}Output: 4Explanation:Consider the length of the rod as 4. Then it can be divided in 2 equal parts, each having
7 min read
Split array into K subsets to maximize their sum of maximums and minimums
Given an integer K and an array A[ ] whose length is multiple of K, the task is to split the elements of the given array into K subsets, each having an equal number of elements, such that the sum of the maximum and minimum elements of each subset is the maximum summation possible. Examples: Input: K = 2, A[ ] = {1, 13, 7, 17, 6, 5} Output: 37 Expla
6 min read
Split an Array A[] into Subsets having equal Sum and sizes equal to elements of Array B[]
Given an array A[] consisting of N integers, the task is to split the array A[] into subsets having equal sum and of length equal to elements in array B[]. Examples: Input: A[] = {17, 13, 21, 20, 50, 29}, B[] = {2, 3, 1} Output: 21 29 17 13 20 50 Input: A[] = { 1, 2, 3, 4, 5, 6}, B[] = { 2, 2, 2} Output: 1 6 2 5 3 4 Approach: Follow the steps below
8 min read
Split array into K non-empty subsets such that sum of their maximums and minimums is maximized
Given two arrays arr[] and S[] consisting of N and K integers, the task is to find the maximum sum of minimum and maximum of each subset after splitting the array into K subsets such that the size of each subset is equal to one of the elements in the array S[]. Examples: Input: arr[] = {1, 13, 7, 17}, S[] = {1, 3}Output: 48Explanation: Consider spl
7 min read
Minimum index to split array into subarrays with co-prime products
Given an array arr[] consisting of N integers, the task is to find the maximum index K such that the product of subarrays {arr[0], arr[K]} and {arr[K + 1], arr[N - 1]} are co-prime. If no such index exists, then print "-1". Examples: Input: arr[] = {2, 3, 4, 5}Output: 2Explanation:Smallest index for partition is 2.Product of left subarray is = 2 *
15 min read
Split N powers of 2 into two subsets such that their difference of sum is minimum
Given an even number N, the task is to split all N powers of 2 into two sets such that the difference of their sum is minimum.Examples: Input: n = 4 Output: 6 Explanation: Here n = 4 which means we have 21, 22, 23, 24. The most optimal way to divide it into two groups with equal element is 24 + 21 in one group and 22 + 23 in another group giving a
6 min read