Find the longest winning streak
A sequence of game results is recorded as wins and losses. Find the length of the longest unbroken streak of wins.
- A streak is a consecutive run of true values.
- A false value breaks any current streak.
- An empty list or all losses returns zero.
WinStreak(results: list<bool>) → int
C# needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
public int WinStreak(List<bool> results) {
}
Worked examples
| Call | Result |
|---|---|
WinStreak(new List<bool> { true, true, false, true }) | 2 |
WinStreak(new List<bool> { false, false, false }) | 0 |
WinStreak(new List<bool> { true, true, true }) | 3 |
WinStreak(new List<bool> { }) | 0 |
Hint
Keep a running counter that resets on every false, and track the best so far.
Reference solution in C#
public int WinStreak(List<bool> results) {
int best = 0, cur = 0;
foreach (bool r in results) {
if (r) { cur++; if (cur > best) best = cur; }
else cur = 0;
}
return best;
}