Enum CoinFlips { Heads, Tails }
int NumberOfFlipsToMakeCoinFlipsAlternate(CoinFlips[] coinFlips){
CoinFlip previousCoinFlip;
int numberOfFlipsNeededToMakeSequenceAlternate = 0;
for(var i =0; i< listOfCoinFlips.length; i++){ if(i==0) { previousCoinFlip = listOfCoinFlips[i]; continue; // deals with the first coin case while in a single for loop, as well as dealing with a trivial sequence of one coin. }
var latestCoinFlip = listOfCoinFlips[i];
if(latestCoinFlip ! = previousCoinFlip) { numberOfFlipsNeededToMakeSequenceAlternate ++; }
return numberOfFlipsNeededToMakeSequenceAlternate; }
If you have HH, you need to flip the second coin. If you have HHT... or HHH..., you still needed to flip that second coin to get a valid sequence. Given that flip has happened, you then decide whether or not you need to flip the third coin (yes and no respectively), and so on. Given the last k are correct, you need to ensure k+1 is.
You can make optimisations, but this can be guaranteed to be done in a single iteration over the array. If it's O(n) it's good enough.