Maximum difference of zeros and ones in binary string

Pattern: 1D DP

medium

Count +1 for each 0 and -1 for each 1. The best substring is the one with the largest sum: Kadane's algorithm. If the string has no 0, the answer is -1.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Return the largest value of (number of 0s - number of 1s) over all substrings, or -1 if the string is all 1s. "11000010001" gives 6. The catalogue has no practice link for this one.

Think first

  • How can a count difference become a sum?
  • Which classic problem finds the best-sum subarray?
  • Why is there a special case?

Hints

    Brute force, and why it fails

    Check every substring: O(n²).

    The key insight

    Turning characters into ±1 makes it Maximum Subarray.

    Dry run

    s = 11000010001. As numbers: -1 -1 +1 +1 +1 +1 -1 +1 +1 +1 -1.

    Step 1 of 3

    The plan

    cur = 0; best = -inf
    for c: cur = max(cur, 0) + (+1 if c == '0' else -1); best = max(best, cur)
    return -1 if no 0 else best
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    One pass.

    Edge cases

    • All 1s: -1.
    • All 0s: n.
    • One character.
    I've built my logic, show the code

    Java

    class Solution {
        public int maxSubstring(String s) {
            int best = Integer.MIN_VALUE, cur = 0;
            for (char c : s.toCharArray()) {        // Kadane on +1 for each 0 and -1 for each 1
                cur = Math.max(cur, 0) + (c == '0' ? 1 : -1);
                best = Math.max(best, cur);
            }
            return best <= 0 && s.indexOf('0') < 0 ? -1 : best;   // all 1s: -1, as the problem asks
        }
    }

    C++

    class Solution {
    public:
        int maxSubstring(string s) {
            int best = INT_MIN, cur = 0;
            for (char c : s) {                      // Kadane on +1 for each 0 and -1 for each 1
                cur = max(cur, 0) + (c == '0' ? 1 : -1);
                best = max(best, cur);
            }
            return s.find('0') == string::npos ? -1 : best;   // all 1s: -1, as the problem asks
        }
    };

    Python

    class Solution:
        def maxSubstring(self, s: str) -> int:
            best, cur = float("-inf"), 0
            for c in s:                             # Kadane on +1 for each 0 and -1 for each 1
                cur = max(cur, 0) + (1 if c == "0" else -1)
                best = max(best, cur)
            return -1 if "0" not in s else best     # all 1s: -1, as the problem asks

    Common mistakes

    • Returning 0 instead of -1 for all 1s.
    • Resetting at the wrong time.

    Similar problems