LeetCode 1422: Maximum Score After Splitting a String Solution

Master LeetCode problem 1422 (Maximum Score After Splitting a String), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1422. Maximum Score After Splitting a String

Problem Explanation

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.

Solution Code

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;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1422 (Maximum Score After Splitting a String)?

This page provides optimized solutions for LeetCode problem 1422 (Maximum Score After Splitting a String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1422 (Maximum Score After Splitting a String)?

The time complexity for LeetCode 1422 (Maximum Score After Splitting a String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1422 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1422 in Java, C++, or Python.

Back to LeetCode Solutions