Split a String in Balanced Strings
Real-world version: Most Even Conveyor SegmentsThe statement here is our own: the same inputs, outputs and technique.
A conveyor gate writes one character per event into log: 'I' when a crate comes in and 'O' when a crate goes out.
Call a run of consecutive events even when it records exactly as many 'I' events as 'O' events. Cut the whole log into consecutive non-empty runs so that every run is even, using every event exactly once and keeping the events in order.
Return the largest number of runs such a cut can produce. The log as a whole is even, so at least one such cut always exists.
Examples
Example 1
- Input
- log = "IOIOIO"
- Output
- 3
Cutting after every second event gives the runs "IO", "IO" and "IO", each recording one arrival and one departure, so three runs is achievable.
Example 2
- Input
- log = "IIOOIO"
- Output
- 2
The runs "IIOO" and "IO" use every event in order and each is even, giving two runs.
Example 3
- Input
- log = "OIOIIO"
- Output
- 3
The runs "OI", "OI" and "IO" are all even, so three runs is achievable. A run may start with a departure.
Constraints
- 2 <= log.length <= 1000
- log[i] is either 'I' or 'O'.
- log records the same number of 'I' events as 'O' events.
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def most_even_segments(log: str) -> int:public int mostEvenSegments(String log)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 12 test cases: 12 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Reorganize StringReal-world version: Paint Line ShuffleMedium
- Maximum Palindromes After OperationsReal-world version: Noticeboard Word StripsMedium
- Construct String With Repeat LimitReal-world version: Largest Banner Under a Run CapMedium
- Largest Palindromic NumberReal-world version: Largest Mirror Number From TilesMedium