LeetCode 1422: Maximum Score After Splitting a String

StringPrefix Sum

Problem Description

Explanation

To find the maximum score after splitting a string into two non-empty substrings, we need to iterate through the string and count the number of zeros and ones. We can then split the string at each position and calculate the score based on the counts of zeros and ones in the left and right substrings. We return the maximum score obtained.

  1. Initialize variables zerosLeft and onesRight to count zeros on the left and ones on the right.
  2. Iterate through the string, counting zeros and ones on the left and right.
  3. Split the string at each position and calculate the score.
  4. Return the maximum score obtained.

Time complexity: O(n) where n is the length of the input string s. Space complexity: O(1) since we are using a constant amount of extra space.

Solutions

class Solution {
    public int maxScore(String s) {
        int zerosLeft = 0, onesRight = 0;
        int maxScore = 0;

        for (int i = 0; i < s.length() - 1; i++) {
            if (s.charAt(i) == '0') {
                zerosLeft++;
            }
            if (s.charAt(i) == '1') {
                onesRight++;
            }

            int score = zerosLeft + onesRight;
            maxScore = Math.max(maxScore, score);
        }

        return maxScore;
    }
}

Loading editor...