Balanced Playlist
Medium · prefix sum
A playlist is written as a string playlist, one capital letter per song, giving the genre of that song. 'R' is a rock song and 'P' is a pop song. Every other letter is some other genre and does not matter.
A part of the playlist is a run of neighbouring songs, with none skipped. A part is balanced when it contains exactly as many rock songs as pop songs. A part with no rock and no pop songs at all is balanced too, because zero equals zero.
Return the number of songs in the longest balanced part. If no part is balanced, return 0.
Examples
Example 1
Input: playlist = "RPPRJ"
Output: 5
The whole playlist has two rock songs, two pop songs and one other, so it is balanced.
Example 2
Input: playlist = "JJ"
Output: 2
There are no rock or pop songs, so both counts are zero and the whole playlist is balanced.
Example 3
Input: playlist = "RRRPJ"
Output: 3
The part "RPJ" has one rock and one pop song. No longer part is balanced, because the first two songs are both rock.
Constraints
- 1 <= len(playlist) <= 5000
- playlist holds only capital letters A to Z