Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find maximum score by splitting binary strings into two parts in Python
Suppose we have a binary string s. We need to split it into two non-empty substrings s1 and s2. The score of this split is the count of "0"s in s1 plus the count of "1"s in s2. We have to find the maximum score we can obtain.
So, if the input is like s = "011001100111", then the output will be 8, because we can split the string like "01100" + "1100111". Then, the score is 3 + 5 = 8.
Algorithm
To solve this, we will follow these steps ?
ones := number of "1"s in s
zeros := 0
ans := 0
-
for i in range 0 to size of s - 2, do
-
if s[i] is same as "0", then
zeros := zeros + 1
-
otherwise,
ones := ones - 1
ans := maximum of ans and (ones + zeros)
-
return ans
Example
Let us see the following implementation to get better understanding ?
def solve(s):
ones = s.count("1")
zeros = 0
ans = 0
for i in range(len(s) - 1):
if s[i] == "0":
zeros += 1
else:
ones -= 1
ans = max(ans, ones + zeros)
return ans
s = "011001100111"
print(solve(s))
The output of the above code is ?
8
How It Works
The algorithm works by iterating through all possible split positions. For each position, we track the count of zeros in the left part and ones in the right part. We maintain a running count to avoid recounting characters for each split position.
Conclusion
This algorithm efficiently finds the maximum score by tracking zeros in the left part and ones in the right part for each possible split. The time complexity is O(n) where n is the length of the string.
