DDSA
Advertisement

1422. Maximum Score After Splitting a String

Time: O(n)
Space: O(1)

Approach

Single pass counting zeros on the left and tracking remaining ones on the right; max score = max(zeros + ones).

1422.cs
C#
// Approach: Single pass counting zeros on the left and tracking remaining ones on the right; max score = max(zeros + ones).
// Time: O(n) Space: O(1)

public class Solution
{
    public int MaxScore(string s)
    {
        int ans = 0;
        int zeros = 0;
        int ones = s.Count(c => c == '1');

        for (int i = 0; i + 1 < s.Length; ++i)
        {
            if (s[i] == '0')
                ++zeros;
            else
                --ones;
            ans = Math.Max(ans, zeros + ones);
        }

        return ans;
    }
}
Advertisement
Was this solution helpful?