Maximum Score After Splitting A String

Introduction

 
In this article, we will solve the leetcode problem #1422, Maximum Score After Splitting a String. The problem statement goes like this,
 
Given a string s of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring). The score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring.
 
For example, if the string s is "011101", then the maximum score after spliting it will be 5. Let's explain that by taking all possible ways to split the string into two non-empty substrings as follows,
  1. left = "0" and right = "11101", score = 1 + 4 = 5 
  2. left = "01" and right = "1101", score = 1 + 3 = 4 
  3. left = "011" and right = "101", score = 1 + 2 = 3 
  4. left = "0111" and right = "01", score = 1 + 1 = 2 
  5. left = "01110" and right = "1", score = 2 + 1 = 3 
And here is how the method is executed in C#,
  1. static void Main(string[] args)  
  2. {  
  3.     var result = maxScore("011101");  
  4.     //result = 5     
  5.     result = maxScore("00111");  
  6.     //result = 5     
  7.     result = maxScore("1111");  
  8.     //result = 3  
  9. }  

Solution

 
The most naive approach to this problem is by precomputing a prefix sum of ones ('1'). And then iterating from left to right counting the number of zeros ('0'), then using the precomputed prefix sum for counting ones ('1'). Update the answer.
 
Here is the C# code for the approach,
  1. static int maxScore(string s)  
  2. {  
  3.     int zeroes = s.ElementAt(0) == '0' ? 1 : 0;  
  4.     int ones = 0;  
  5.     for (int i = 1; i < s.Length; i++)  
  6.     {  
  7.         if (s.ElementAt(i) == '1')  
  8.         {  
  9.             ones++;  
  10.         }  
  11.     }  
  12.     int maxScore = zeroes + ones;  
  13.     for (int i = 1; i < s.Length - 1; i++)  
  14.     {  
  15.         if (s.ElementAt(i) == '0')  
  16.         {  
  17.             zeroes++;  
  18.         }  
  19.         else  
  20.         {  
  21.             ones--;  
  22.         }  
  23.         maxScore = Math.Max(maxScore, zeroes + ones);  
  24.     }  
  25.     return maxScore;  
  26. }