Posted on

Maximum Score After Splitting a String

C++ Solution

class Solution {
public:
    int maxScore(string s) {
        int ones = count(s.begin(), s.end(), '1'); // Total 1's in the string
        int zeros = 0, result = 0; // Initialize count of zeros and result

        for (int i = 0; i < s.size() - 1; i++) { // Iterate but exclude the last split point
            if (s[i] == '1') 
                ones--; // Move '1' from right to left
            else 
                zeros++; // Increment count of '0's in the left part

            result = max(result, zeros + ones); // Update the maximum score
        }

        return result; // Return the best score
    }
};