Skip to content
Related Articles
Longest subsequence possible that starts and ends with 1 and filled with 0 in the middle
• Difficulty Level : Expert
• Last Updated : 03 Jun, 2021

Given a binary string s, the task is to find the length of the longest subsequence that can be divided into three substrings such that the first and third substrings are either empty or filled with 1 and the substring at the middle is either empty or filled with 0.

Examples:

Input: s = “1001”
Output:
Explanation:
The entire string can be divided into the desired three parts: “1”, “00”, “1”.

Input: s = “010”
Output:
Explanation:
The subsequences “00”, “01” and “10” can be split into three desired parts {“”, “00”, “”}, {“”, “0”, “1”} and {“1”, “0”, “”}

Approach:
To solve the problem, we need to follow the steps given below:

• Firstly, pre-compute and store in prefix arrays, the occurrences of ‘1’ and ‘0’ respectively.
• Initialize two integers i and j, where i will be the point of partition between the first and second string and j will be the point of partition between the second and third strings.
• Iterate over all possible values of i & j (0 <= i < j <=n) and find the maximum possible length of the subsequence possible which satisfies the given condition.

Below is the implementation of the above approach:

## C++

 `// C++ Program to find the``// longest subsequence possible``// that starts and ends with 1``// and filled with 0 in the middle` `#include ``using` `namespace` `std;` `int` `longestSubseq(string s, ``int` `length)``{``    ``// Prefix array to store the``    ``// occurences of '1' and '0'``    ``int` `ones[length + 1], zeroes[length + 1];` `    ``// Initialise prefix arrays with 0``    ``memset``(ones, 0, ``sizeof``(ones));``    ``memset``(zeroes, 0, ``sizeof``(zeroes));` `    ``// Iterate over the length of the string``    ``for` `(``int` `i = 0; i < length; i++) {` `        ``// If current character is '1'``        ``if` `(s[i] == ``'1'``) {``            ``ones[i + 1] = ones[i] + 1;``            ``zeroes[i + 1] = zeroes[i];``        ``}` `        ``// If current character is '0'``        ``else` `{``            ``zeroes[i + 1] = zeroes[i] + 1;``            ``ones[i + 1] = ones[i];``        ``}``    ``}` `    ``int` `answer = INT_MIN;``    ``int` `x = 0;` `    ``for` `(``int` `i = 0; i <= length; i++) {``        ``for` `(``int` `j = i; j <= length; j++) {``            ``// Add '1' available for``            ``// the first string``            ``x += ones[i];` `            ``// Add '0' available for``            ``// the second string``            ``x += (zeroes[j] - zeroes[i]);` `            ``// Add '1' available for``            ``// the third string``            ``x += (ones[length] - ones[j]);` `            ``// Update answer``            ``answer = max(answer, x);` `            ``x = 0;``        ``}``    ``}` `    ``// Print the final result``    ``cout << answer << endl;``}` `// Driver Code``int` `main()``{` `    ``string s = ``"10010010111100101"``;` `    ``int` `length = s.length();` `    ``longestSubseq(s, length);` `    ``return` `0;``}`

## Java

 `// Java program to find the``// longest subsequence possible``// that starts and ends with 1``// and filled with 0 in the middle``import` `java.io.*;` `class` `GFG{` `static` `void` `longestSubseq(String s,``                          ``int` `length)``{``    ` `    ``// Prefix array to store the``    ``// occurences of '1' and '0'``    ``int``[] ones = ``new` `int``[length + ``1``];``    ``int``[] zeroes = ``new` `int``[length + ``1``];` `    ``// Iterate over the length of``    ``// the string``    ``for``(``int` `i = ``0``; i < length; i++)``    ``{``        ` `        ``// If current character is '1'``        ``if` `(s.charAt(i) == ``'1'``)``        ``{``            ``ones[i + ``1``] = ones[i] + ``1``;``            ``zeroes[i + ``1``] = zeroes[i];``        ``}` `        ``// If current character is '0'``        ``else``        ``{``            ``zeroes[i + ``1``] = zeroes[i] + ``1``;``            ``ones[i + ``1``] = ones[i];``        ``}``    ``}` `    ``int` `answer = Integer.MIN_VALUE;``    ``int` `x = ``0``;` `    ``for``(``int` `i = ``0``; i <= length; i++)``    ``{``        ``for``(``int` `j = i; j <= length; j++)``        ``{``            ` `            ``// Add '1' available for``            ``// the first string``            ``x += ones[i];` `            ``// Add '0' available for``            ``// the second string``            ``x += (zeroes[j] - zeroes[i]);` `            ``// Add '1' available for``            ``// the third string``            ``x += (ones[length] - ones[j]);` `            ``// Update answer``            ``answer = Math.max(answer, x);``            ``x = ``0``;``        ``}``    ``}` `    ``// Print the final result``    ``System.out.println(answer);``}` `// Driver code``public` `static` `void` `main(String[] args)``{``    ``String s = ``"10010010111100101"``;``    ``int` `length = s.length();` `    ``longestSubseq(s, length);``}``}` `// This code is contributed by offbeat`

## Python3

 `# Python3 program to find the``# longest subsequence possible``# that starts and ends with 1``# and filled with 0 in the middle``import` `sys` `def` `longestSubseq(s, length):``    ` `    ``# Prefix array to store the``    ``# occurences of '1' and '0'``    ``# Initialise prefix arrays with 0``    ``ones ``=` `[``0` `for` `i ``in` `range``(length ``+` `1``)]``    ``zeroes ``=` `[``0` `for` `i ``in` `range``(length ``+` `1``)]` `    ``# Iterate over the length of the string``    ``for` `i ``in` `range``(length):``        ` `        ``# If current character is '1'``        ``if``(s[i] ``=``=` `'1'``):``            ``ones[i ``+` `1``] ``=` `ones[i] ``+` `1``            ``zeroes[i ``+` `1``] ``=` `zeroes[i]` `        ``# If current character is '0'``        ``else``:``            ``zeroes[i ``+` `1``] ``=` `zeroes[i] ``+` `1``            ``ones[i ``+` `1``] ``=` `ones[i]` `    ``answer ``=` `-``sys.maxsize ``-` `1``    ``x ``=` `0` `    ``for` `i ``in` `range``(length ``+` `1``):``        ``for` `j ``in` `range``(i, length ``+` `1``):``            ` `            ``# Add '1' available for``            ``# the first string``            ``x ``+``=` `ones[i]` `            ``# Add '0' available for``            ``# the second string``            ``x ``+``=` `(zeroes[j] ``-` `zeroes[i])` `            ``# Add '1' available for``            ``# the third string``            ``x ``+``=` `(ones[length] ``-` `ones[j])` `            ``# Update answer``            ``answer ``=` `max``(answer, x)``            ``x ``=` `0` `    ``# Print the final result``    ``print``(answer)` `# Driver Code``S ``=` `"10010010111100101"``length ``=` `len``(S)` `longestSubseq(S, length)` `# This code is contributed by avanitrachhadiya2155`

## C#

 `// C# program to find the``// longest subsequence possible``// that starts and ends with 1``// and filled with 0 in the middle``using` `System;` `class` `GFG{` `static` `void` `longestSubseq(String s,``                          ``int` `length)``{``    ` `    ``// Prefix array to store the``    ``// occurences of '1' and '0'``    ``int``[] ones = ``new` `int``[length + 1];``    ``int``[] zeroes = ``new` `int``[length + 1];` `    ``// Iterate over the length of``    ``// the string``    ``for``(``int` `i = 0; i < length; i++)``    ``{``        ` `        ``// If current character is '1'``        ``if` `(s[i] == ``'1'``)``        ``{``            ``ones[i + 1] = ones[i] + 1;``            ``zeroes[i + 1] = zeroes[i];``        ``}` `        ``// If current character is '0'``        ``else``        ``{``            ``zeroes[i + 1] = zeroes[i] + 1;``            ``ones[i + 1] = ones[i];``        ``}``    ``}` `    ``int` `answer = ``int``.MinValue;``    ``int` `x = 0;` `    ``for``(``int` `i = 0; i <= length; i++)``    ``{``        ``for``(``int` `j = i; j <= length; j++)``        ``{``            ` `            ``// Add '1' available for``            ``// the first string``            ``x += ones[i];` `            ``// Add '0' available for``            ``// the second string``            ``x += (zeroes[j] - zeroes[i]);` `            ``// Add '1' available for``            ``// the third string``            ``x += (ones[length] - ones[j]);` `            ``// Update answer``            ``answer = Math.Max(answer, x);``            ``x = 0;``        ``}``    ``}` `    ``// Print the readonly result``    ``Console.WriteLine(answer);``}` `// Driver code``public` `static` `void` `Main(String[] args)``{``    ``String s = ``"10010010111100101"``;``    ``int` `length = s.Length;` `    ``longestSubseq(s, length);``}``}` `// This code is contributed by Amit Katiyar`

## Javascript

 ``
Output:
`12`

Time Complexity: O(N2)
Auxiliary Space: O(N)

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.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes

My Personal Notes arrow_drop_up