Maximum length of segments of 0’s and 1’s

Given a string comprising of ones and zeros. The task is to find the maximum length of the segments of string such that a number of 1 in each segment is greater than 0.

Note: Each segment taken should be distinct. Index starts from 0.

Examples:

Input: str = “100110001010001”
Output: 9
First segment from index 0 to 4 (10011), total length = 5
Second segment from index 8 to 10 (101), total length = 3
Third segment from index 14 till 14 (1), total length = 1,

Hence asnwer is 5 + 3 + 1 = 9


Input:
str = “0010111101100000”
Output: 13
The maximum length can be formed by taking segment
from index 0 till index 12 (0010111101100),
i.e. of total length = 13

Approach:

  1. If start == n, limiting condition arises, return 0.
  2. Run a loop from start till n, computing for each subarray till n.
  3. If character is 1 then increment the count of 1 else increment the count of 0.
  4. If count of 1 is greater than 0, recursively call the function for index (k+1) i.e. next index and add the remaining length i.e. k-start+1.
  5. Else only recursively call the function for next index k+1.
  6. Return dp[start].

Below is the implementation of above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
  
// Recursive Function to find total length of the array
// Where 1 is greater than zero
int find(int start, string adj, int n, int dp[])
{
    // If reaches till end
    if (start == n)
        return 0;
  
    // If dp is saved
    if (dp[start] != -1)
        return dp[start];
  
    dp[start] = 0;
    int one = 0, zero = 0, k;
  
    // Finding for each length
    for (k = start; k < n; k++) {
  
        // If the character scanned is 1
        if (adj[k] == '1')
            one++;
        else
            zero++;
  
        // If one is greater than zero, add total
        // length scanned till now
        if (one > zero)
            dp[start] = max(dp[start], find(k + 1, adj, n, dp)
                                           + k - start + 1);
  
        // Continue with next length
        else
            dp[start] = max(dp[start], find(k + 1, adj, n, dp));
    }
  
    // Return the value for start index
    return dp[start];
}
  
// Driver Code
int main()
{
    string adj = "100110001010001";
  
    // Size of string
    int n = adj.size();
    int dp[n + 1];
    memset(dp, -1, sizeof(dp));
    // Calling the function to find the value of function
  
    cout << find(0, adj, n, dp) << endl;
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of
// above approach
import java.util.*;
import java.lang.Math;
  
class GFG
{
// Recursive Function to find 
// total length of the array 
// Where 1 is greater than zero 
public static int find(int start, String adj, 
                       int n, int dp[])
{
          
    // If reaches till end 
    if (start == n) 
        return 0
      
    // If dp is saved 
    if (dp[start] != -1
        return dp[start]; 
      
    dp[start] = 0
    int one = 0, zero = 0, k;
      
    // Finding for each length 
    for (k = start; k < n; k++) 
    
      
        // If the character scanned is 1 
        if (adj.charAt(k) == '1'
            one++; 
        else
            zero++; 
      
        // If one is greater than 
        // zero, add total length
        // scanned till now 
        if (one > zero) 
            dp[start] = Math.max(dp[start], 
                            find(k + 1, adj, n, dp) + 
                                 k - start + 1); 
      
        // Continue with next length 
        else
            dp[start] = Math.max(dp[start], 
                            find(k + 1, adj, n, dp)); 
    }
      
    return dp[start];
}
  
// Driver code
public static void main (String[] args) 
{
    String adj = "100110001010001"
  
    // Size of string 
    int n = adj.length(); 
    int dp[] = new int[n + 1]; 
    Arrays.fill(dp, -1);
      
        // Calling the function to find
        // the value of function
        System.out.println(find(0, adj, n, dp));
}
}
  
// This code is contributed 
// by Kirti_Mangal

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 implementation of above approach
  
# Recursive Function to find total length 
# of the array where 1 is greater than zero
def find(start, adj, n, dp):
      
    # If reaches till end
    if (start == n):
        return 0
  
    # If dp is saved
    if (dp[start] != -1):
        return dp[start]
  
    dp[start] = 0
    one = 0
    zero = 0
      
    # Finding for each length
    for k in range(start, n, 1):
          
        # If the character scanned is 1
        if (adj[k] == '1'):
            one += 1
        else:
            zero += 1
  
        # If one is greater than zero, add 
        # total length scanned till now
        if (one > zero):
            dp[start] = max(dp[start], 
                            find(k + 1, adj, n, dp) +
                                 k - start + 1)
  
        # Continue with next length
        else:
            dp[start] = max(dp[start], 
                            find(k + 1, adj, n, dp))
  
    # Return the value for start index
    return dp[start]
  
# Driver Code
if __name__ == '__main__':
    adj = "100110001010001"
  
    # Size of string
    n = len(adj)
    dp = [-1 for i in range(n + 1)]
      
    # Calling the function to find the 
    # value of function
    print(find(0, adj, n, dp))
  
# This code is contributed by
# Surendra_Gangwar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of above approach 
using System; 
    
class GFG 
    // Recursive Function to find total length of the array 
    // Where 1 is greater than zero 
    public static int find(int start, string adj, int n, int[] dp) 
    
        // If reaches till end 
        if (start == n) 
            return 0; 
        
        // If dp is saved 
        if (dp[start] != -1) 
            return dp[start]; 
        
        dp[start] = 0; 
        int one = 0, zero = 0, k; 
        
        // Finding for each length 
        for (k = start; k < n; k++) { 
        
            // If the character scanned is 1 
            if (adj[k] == '1'
                one++; 
            else
                zero++; 
        
            // If one is greater than zero, add total 
            // length scanned till now 
            if (one > zero) 
                dp[start] = Math.Max(dp[start], find(k + 1, adj, n, dp) 
                                               + k - start + 1); 
        
            // Continue with next length 
            else
                dp[start] = Math.Max(dp[start], find(k + 1, adj, n, dp)); 
        
        
        // Return the value for start index 
        return dp[start]; 
    
        
    // Driver Code
    static void Main() 
    
        string adj = "100110001010001"
    
        // Size of string 
        int n = adj.Length; 
        int[] dp = new int[n + 1]; 
        for(int i = 0; i <= n; i++)
            dp[i] = -1;
        // Calling the function to find the value of function 
        
        Console.Write(find(0, adj, n, dp) + "\n"); 
    }
    //This code is contributed by DrRoot_
}

chevron_right


PHP

$zero)
$dp[$start] = max($dp[$start],
find($k + 1, $adj, $n, $dp) +
$k – $start + 1);

// Continue with next length
else
$dp[$start] = max($dp[$start],
find($k + 1, $adj, $n, $dp));
}

// Return the value for $start index
return $dp[$start];
}

// Driver Code
$adj = “100110001010001”;

// Size of string
$n = strlen($adj);
$dp = array_fill(0, $n + 1, -1);

// Calling the function
// to find the value of function
echo find(0, $adj, $n, $dp);

// This code is contributed by ihritik
?>

Output:

9


My Personal Notes arrow_drop_up

Coder only XD Do send reference if contacting me

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.