FOR FREE CONTENT

Longest streaks

Back to Programming

Description

A can was to used numerous time. You need to find the longest streaks of tosses resulting Heads and the longest streak of tosses resulting in Tails.

Consider the following example of 7 tosses.

Heads, Heads, Tails, tails, Heads, Heads, Heads

∴ The longest Heads streak was 3 and longest tail streak was 2.

 

Algorithm

Heads

2

Heads

 

Tails

2

Tails

Heads

3

Heads

Heads

We will count number of heads / tails from beginning continuously till a change from head to tail or tail to head is found.

We will record the current number of counts of heads and tails.

We will find the maximum of all current number of counts of heads and tails and return it.

Algorithm:

Step 1: Initialize 4 variables with 0 / h, t, f1, f2 = 0

Step 2: Run a loop till the length of toss is reached

Step 3: If current = head

                   increase head count

                   find the max of all counting of tails

                   again max count of t initialize to 0

             else

                   increase tail count

                   find the max of all counting of heads

                   again make count of h initialize to 0

Step 4: Repeat Step 2 to 3 till condition fails

Step 5: Return the max values

Code

Time Complexity: O(n)           /n = length of toss

Space: O(1)