Loading...
Loading...
A class register marks each of n days as P (present) or A (absent) for one student. The class teacher wants to show the longest stretch of consecutive days in which the student was present on exactly as many days as absent.
Print the length of the longest such stretch. If there is none, print 0.
P or A.0.Example 1
Input
9 PPAPAAAAP
Output
6
Days 1–6 (PPAPAA) have three P and three A. No longer stretch is balanced.
Example 2
Input
3 PPP
Output
0
There is no absent day, so no stretch is balanced.
Try the problem first. Open one hint at a time.
Count P as +1 and A as −1. A stretch is balanced when its total is 0.
Keep a running score. If the score after day j equals the score after an earlier day i, then days i + 1 to j are balanced.
Store the first day each score appears in a HashMap; the earliest match gives the longest stretch.
Store score 0 at day 0 before you start, so stretches that begin on day 1 are found.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor