Length of the longest alternating sub array

Given an array of integer numbers, write a program to find the length of the longest alternating sub array from the given array.

For example:

Input: 
arr = {-10, -2, -2, 2, 4, -6 }

Output: 3 
The subarray {-2, 2, 4}

Solution:

using System;
using System;

namespace Array 
{
 class Program 
 {
   public static void Main()
   {
     int[] a = { -10, -2, -2, 2, -1, -6};
     Console.Write(AlternatingSubArray(a));
     Console.ReadLine();
   }

  static int AlternatingSubArray(int[] arr) 
  {
   var result = 1;
   var counter = 1;
   for (var i = 1; i < arr.Length; i++) 
   {
    if (arr[i] * arr[i - 1] < 0) 
    {
     counter++;
     result = Math.Max(result, counter);
    } 
    else 
    {
     counter = 1;
    }
   }
   return result;
  }
 }
}

Leave a Reply

Your email address will not be published. Required fields are marked *