This is how i thought about it
- First, you need to know if you are starting to start or starting from a low level. for example:
1-2-1 or 2-1-2 . You may not even have a familiar couple. - Then you count each number afterwards to see if it belongs in a sequence, taking into account the current direction.
- Each time the sequence is interrupted, you need to start again by checking the direction.
I'm not sure if it is possible that from a number that you have already seen, choosing a different start number can POSSIBLY generate a longer sequence. Maybe there is a theorem that shows that this is impossible; perhaps this is obvious, and I'm thinking too much. But I donโt think itโs possible, because the reason the sequence is broken is because you have two high or two low, and there is no way around this.
I assumed the following cases
{} - no elements, returns 0{1} - the only element, returns 0{1, 1, 1} - there is no alternating sequence, returns 0
No input restrictions other than what C # expects. It can probably be compressed. Not sure if there is a way to capture the logic of changing directions without explicitly tracking the direction.
static int max_alternate(int[] numbers) { int maxCount = 0; int count = 0; int dir = 0; // whether we're going up or down for (int j = 1; j < numbers.Length; j++) { // don't know direction yet if (dir == 0) { if (numbers[j] > numbers[j-1]) { count += 2; // include first number dir = 1; // start low, up to high } else if (numbers[j] < numbers[j-1]) { count += 2; dir = -1; // start high, down to low } } else { if (dir == -1 && numbers[j] > numbers[j-1]) { count += 1; dir = 1; // up to high } else if (dir == 1 && numbers[j] < numbers[j-1]) { count += 1; dir = -1; // down to low } else { // sequence broken if (count > maxCount) { maxCount = count; } count = 0; dir = 0; } } } // final check after loop is done if (count > maxCount) { maxCount = count; } return maxCount; }
And some test cases with results based on my understanding of the issue and some assumptions.
static void Main(string[] args) { int[] nums = { 1}; // base case == 0 int[] nums2 = { 2, 1 }; // even case == 2 int[] nums3 = { 1, 2, 1 }; // odd case == 3 int[] nums4 = { 2, 1, 2 }; // flipped starting == 3 int[] nums5 = { 2, 1, 2, 2, 1, 2, 1 }; // broken seqeuence == 4 int[] nums6 = { 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 2, 1, 2, 1 }; // long sequence == 14 Console.WriteLine(max_alternate(nums)); Console.WriteLine(max_alternate(nums2)); Console.WriteLine(max_alternate(nums3)); Console.WriteLine(max_alternate(nums4)); Console.WriteLine(max_alternate(nums5)); Console.WriteLine(max_alternate(nums6)); Console.ReadLine(); }