Maximum binary string after change
January 11, 2023
greedyProblem URL: Maximum binary string after change
We will use greedy approach to solve the problem. We will find the first 0
and change it to 1
. Then we will find the next 0
and change it to 1
. We will repeat this process until we find the last 0
. Finally we will return the binary string.
class Solution:
def maximumBinaryString(self, binary: str) -> str:
if '0' not in binary:
return binary
n = len(binary)
k = binary.count('1', binary.find('0'))
return '1' * (n-k-1) + '0' + '1' * k
Time complexity: O(n)
Space complexity: O(1)