Tutte le sfide
Facile 0 risolte 0% di accettazione

Coin Toss Streaks

Find the longest streak of heads, the longest streak of tails and the number of streaks in a coin toss record.

Cosa imparerai

  • Split a sequence into maximal runs
  • Track the best run for each value
  • Count runs

Problema

Mostra traduzione

A probability lab flips a coin many times and writes the results as a string of H (heads) and T (tails). A streak is a maximal group of consecutive equal results; HHTHHH has the streaks HH, T and HHH. Students are often surprised how long the longest streak in a random record is, so the lab measures it.

Implement coin_toss_streaks(tosses).

Input

tosses: The results in order, using only H and T.

Output

Return [longest_heads, longest_tails, streaks]: the length of the longest heads streak, the length of the longest tails streak (0 if that side never comes up) and the total number of streaks.

Vincoli

0 ≤ length of tosses ≤ 100,000

Esempi

Esempio 1
Input:
tosses = "HHTHHH"

Output atteso:
expected = [3, 1, 3]
Input:
std::string tosses = "HHTHHH";

Output atteso:
std::vector<long long> expected = {3, 1, 3};
Input:
string tosses = "HHTHHH";

Output atteso:
long[] expected = new long[] {3, 1, 3};

Spiegazione

The streaks are HH, T and HHH, so the longest heads streak is 3, the longest tails streak is 1, and there are 3 streaks.

Esempio 2
Input:
tosses = "TTTT"

Output atteso:
expected = [0, 4, 1]
Input:
std::string tosses = "TTTT";

Output atteso:
std::vector<long long> expected = {0, 4, 1};
Input:
string tosses = "TTTT";

Output atteso:
long[] expected = new long[] {0, 4, 1};

Spiegazione

Heads never comes up, so its longest streak is 0; there is one tails streak of length 4: [0, 4, 1].

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

A new streak starts at index 0 and wherever a toss differs from the one before.

Suggerimento 2

Keep one best length for heads and one for tails.

Suggerimento 3

An empty string has no streaks at all.

Complessità attesa

O(n) time, O(1) extra space

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

Ancora nessuna soluzione superata. Risolvila e prendi il primo posto.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.