Skip to content

Commit

Permalink
Space-optimized solution to "Maximum Score After Splitting a String" …
Browse files Browse the repository at this point in the history
…problem
  • Loading branch information
dkoval committed Jan 1, 2025
1 parent 2fae1fd commit 717e2ad
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,32 @@ public int maxScore(String s) {
return best;
}
}

// O(N) time | O(1) space
class MaximumScoreAfterSplittingStringRev3 implements MaximumScoreAfterSplittingString {

@Override
public int maxScore(String s) {
final var n = s.length();

var rightOnes = 0;
for (var i = 0; i < n; i++) {
if (s.charAt(i) == '1') {
rightOnes++;
}
}

var best = 0;
var leftZeros = 0;
for (var i = 0; i < n - 1; i++) {
if (s.charAt(i) == '0') {
leftZeros++;
} else {
rightOnes--;
}
best = Math.max(best, leftZeros + rightOnes);
}
return best;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.github.dkoval.leetcode.challenge

import com.github.dkoval.leetcode.challenge.MaximumScoreAfterSplittingString.MaximumScoreAfterSplittingStringRev1
import com.github.dkoval.leetcode.challenge.MaximumScoreAfterSplittingString.MaximumScoreAfterSplittingStringRev2
import com.github.dkoval.leetcode.challenge.MaximumScoreAfterSplittingString.*
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.extension.ExtensionContext
Expand Down Expand Up @@ -48,6 +47,19 @@ internal class MaximumScoreAfterSplittingStringTest {
MaximumScoreAfterSplittingStringRev2().test(s, expected)
}
}

@Nested
inner class MaximumScoreAfterSplittingStringRev3Test {

@ParameterizedTest
@ArgumentsSource(InputArgumentsProvider::class)
fun `should return the maximum score after splitting the string into two non-empty substrings`(
s: String,
expected: Int
) {
MaximumScoreAfterSplittingStringRev3().test(s, expected)
}
}
}

private fun MaximumScoreAfterSplittingString.test(s: String, expected: Int) {
Expand Down

0 comments on commit 717e2ad

Please sign in to comment.