2 minutes
Leetcode 1422
1422. Maximum Score After Splitting a String
The idea of the first solution is pretty simple, and the second solution is based on the first solution.
The idea of the first solution is:
- We loop through
sand add all the numbers to a counter callednumberOfOnesto count the number of ones. We do this by using ASCII. The ASCII of0is48, and the ASCII of1is49, so we can get theintofs[i]and then subtract48from it to get0or1. If it is0s[i] = '0'and if it is1s[i] = '1'. - If the first element is a
'0'we add one tonumberOfZerosand if it is a'1'we can subtract one fromnumberOfOnesbecause the split string starts with a substring of length1on the left and a substring of length(len(s) - 1) - 1. - Then we can loop through
1tolen(s) - 1and add one tonumberOfZerosor subtract one from thenumberOfOnes, and then check whether thenumberOfZeros + numberOfOnesis greater thanmaximum, if so makemaximumequal tonumberOfZeros + numberOfOnes.
The idea of the second solution is: We do the same thing as the first solution, but we combine numberOfZeros and numberOfOnes into a variable called sum.
The First Code:
func maxScore(s string) int {
numberOfOnes := 0
numberOfZeros := 0
maximum := 0
for _, i := range s {
numberOfOnes += int(i) - 48
}
numberOfZeros, numberOfOnes =
addAndSubtractFromOnesAndZeros(s, numberOfZeros, numberOfOnes, 0)
maximum = numberOfOnes + numberOfZeros
for i := 1; i < len(s)-1; i++ {
numberOfZeros, numberOfOnes =
addAndSubtractFromOnesAndZeros(s, numberOfZeros, numberOfOnes, i)
if numberOfOnes + numberOfZeros > maximum {
maximum = numberOfOnes + numberOfZeros
}
}
return maximum
}
func addAndSubtractFromOnesAndZeros(s string,
numberOfZeros, numberOfOnes, i int) (int, int) {
if s[i] == '0' {
return numberOfZeros + 1, numberOfOnes
}
return numberOfZeros, numberOfOnes - 1
}
The Second Code:
func maxScore(s string) int {
maximum := 0
sum := 0
for _, i := range s {
sum += int(i) - 48
}
sum = addAndSubtractFromOnesAndZeros2(s, sum, 0)
maximum = sum
for i := 1; i < len(s)-1; i++ {
sum = addAndSubtractFromOnesAndZeros2(s, sum, i)
if sum > maximum {
maximum = sum
}
}
return maximum
}
func addAndSubtractFromOnesAndZeros2(s string, sum, i int) int {
if s[i] == '0' {
return sum + 1
}
return sum - 1
}
Read other posts