All puzzles
Per page
J
Streak · Maximum · String

Longest streak

Each letter of flips is "H" or "T". Return the length of the longest run of "H" in a row.

longestStreak("HHTHHHTH") returns 3.

16 strips: J1 to J16

}
J1
for (int i = 0; i < flips.length(); i++) {
J2
return best;
J3
public static int longestStreak(String flips) {
J4
}
J5
if (flips.substring(i, i + 1).equals("H")) {
J6
current = 0;
J7
if (current > best) {
J8
int best = 0;
J9
best = 0;
J10
current++;
J11
}
J12
} else {
J13
}
J14
int current = 0;
J15
best = current;
J16

Answer key: J. Longest streak

Order: J4, J15, J9, J2, J6, J11, J8, J16, J1, J13, J7, J14, J12, J3, J5. Extra: J10

Lines with the same mark can go in either order.

public static int longestStreak(String flips) {
	int current = 0;
	int best = 0;
	for (int i = 0; i < flips.length(); i++) {
		if (flips.substring(i, i + 1).equals("H")) {
			current++;
			if (current > best) {
				best = current;
			}
		} else {
			current = 0;
		}
	}
	return best;
}

Extra strip: best = 0;. A "T" ends the current run only. Setting best to 0 forgets the longest run found so far.