All problems
0762EasyStringGreedyCounting

Most Even Conveyor Segments

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1221Split a String in Balanced Strings

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def most_even_segments(log: str) -> int:
Java
public int mostEvenSegments(String log)
September 7
Apply