Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting alternating numbers in an array

Tags:

c#

algorithm

Given an array of integers...

var numbers = new int[] { 1,2,1,2,1,2,1,2,1,2,1,2,1,2,2,2,1,2,1 };

I need to determine a the maximum sequence of numbers that alternate up then down or down then up.

Not sure the best way to approach this, the process psuedo wise strikes me as simple but materializing code for it is evading me.

The key is the fact we are looking for max sequence, so while the above numbers could be interpreted in many ways, like a sequence of seven up-down-up and seven down-up-down the important fact is starting with the first number there is a down-up-down sequence that is 14 long.

Also I should not that we count the first item, 121 is a sequence of length 3, one could argue the sequence doesn't begin until the second digit but lets not split hairs.

like image 554
keithwarren7 Avatar asked Aug 07 '12 21:08

keithwarren7


1 Answers

This seems to work, it assumes that the length of numbers is greater than 4 (that case should be trivial anyways):

var numbers = new int[] { 1,2,1,2,1,2,1,2,1,2,1,2,1,2,2,2,1,2,1 };
int count = 2, max = 0;
for (int i = 1; i < numbers.Length - 1; i++)
{

    if ((numbers[i - 1] < numbers[i] && numbers[i + 1] < numbers[i]) ||
                    (numbers[i - 1] > numbers[i] && numbers[i + 1] > numbers[i]))
    {
        count++;
        max = Math.Max(count, max);
    }
    else if ((numbers[i - 1] < numbers[i]) || (numbers[i - 1] > numbers[i])
                || ((numbers[i] < numbers[i + 1]) || (numbers[i] > numbers[i + 1])))
    {
        max = Math.Max(max, 2);
        count = 2;
    }
}
Console.WriteLine(max); // 14
like image 196
NominSim Avatar answered Oct 13 '22 00:10

NominSim