Longest open run
A venue log uses O for an open hour and X for a closed hour. Read the log and print the longest consecutive run of O characters. If no hour was open, print zero.
Input
One line of 1 to 200 characters, each O or X.
Output
One integer: the longest consecutive open run.
Example 1
Input
OOXOOOXXO
Output
3
The middle three open hours form the longest run.
Constraints
- 1 <= log length <= 200
- The log contains only O and X
Hints
Hint 1 of 3
Track the current run separately from the best run.
Hint 2 of 3
Reset current when the status is X.
Hint 3 of 3
Update best after incrementing current.
Solution
Show a reference solution and explanation
const log = readline();
let best = 0;
let current = 0;
for (const status of log) {
if (status === 'O') {
current++;
best = Math.max(best, current);
} else {
current = 0;
}
}
console.log(best);
Why it works
The current counter describes the run ending at the present character. A closed hour breaks it, while the best counter keeps the largest run seen before that reset.
Lesson for this exercise: Loops in JavaScript: for, while, for...of and for...in