Length of the longest alternating subarray

Given an array of N including positive and negative numbers only. The task is to find the length of the longest alternating (means negative-positive-negative or positive-negative-positive) subarray present in the array.Â
Examples:Â
Input: a[] = {-5, -1, -1, 2, -2, -3}
Output: 3
The subarray {-1, 2, -2}
Input: a[] = {1, -5, 1, -5}
Output: 4
Approach: The following steps are followed to solve the problem:Â
- Initially initialize cnt as 1.
- Iterate among the array elements, and check if it has an alternate sign.
- Increase the cnt by 1 if it has an alternate sign.
- If it does not has an alternate sign, then re-initialize cnt by 1.
Below is the implementation of the above approach:Â
C++
// C++ program to find the longest alternating// subarray in an array of N number#include <bits/stdc++.h>using namespace std;Â
// Function to find the longest subarrayint longestAlternatingSubarray(int a[], int n){    // Length of longest alternating    int longest = 1;    int cnt = 1;Â
    // Iterate in the array    for (int i = 1; i < n; i++) {Â
        // Check for alternate        if (a[i] * a[i - 1] < 0) {            cnt++;            longest = max(longest, cnt);        }        else            cnt = 1;    }    return longest;}Â
/* Driver program to test above functions*/int main(){Â Â Â Â int a[] = { -5, -1, -1, 2, -2, -3 };Â Â Â Â int n = sizeof(a) / sizeof(a[0]);Â
    // Function to find the longest subarray    cout << longestAlternatingSubarray(a, n);    return 0;} |
Java
// Java program to find the longest alternating // subarray in an array of N numberclass GFG {Â
    // Function to find the longest subarray     static int longestAlternatingSubarray(int a[], int n)     {         // Length of longest alternating         int longest = 1;         int cnt = 1;              // Iterate in the array         for (int i = 1; i < n; i++)         {                  // Check for alternate             if (a[i] * a[i - 1] < 0)            {                 cnt++;                 longest = Math.max(longest, cnt);             }             else                cnt = 1;         }         return longest;     }          /* Driver program to test above functions*/    public static void main (String[] args)    {         int a[] = { -5, -1, -1, 2, -2, -3 };         int n = a.length ;              // Function to find the longest subarray         System.out.println(longestAlternatingSubarray(a, n));    } }Â
// This code is contributed by Ryuga |
Python 3
# Python3 program to find the longest alternating # subarray in an array of N number Â
# Function to find the longest subarray def longestAlternatingSubarray(a, n):         # Length of longest alternating     longest = 1    cnt = 1Â
    # Iterate in the array    i = 1    while i < n: Â
        # Check for alternate         if (a[i] * a[i - 1] < 0):            cnt = cnt + 1            longest = max(longest, cnt)                  else:            cnt = 1        i = i + 1         return longest Â
# Driver Codea = [ -5, -1, -1, 2, -2, -3 ]n = len(a)Â
# Function to find the longest subarray print(longestAlternatingSubarray(a, n))Â
# This code is contributed # by shashank_sharma |
C#
// C# program to find the longest alternating// subarray in an array of N numberusing System;class GFG{Â
// Function to find the longest subarraystatic int longestAlternatingSubarray(int []a,                                       int n){    // Length of longest alternating    int longest = 1;    int cnt = 1;Â
    // Iterate in the array    for (int i = 1; i < n; i++)     {Â
        // Check for alternate        if (a[i] * a[i - 1] < 0)        {            cnt++;            longest = Math.Max(longest, cnt);        }        else            cnt = 1;    }    return longest;}Â
// Driver Codepublic static void Main(){Â Â Â Â int []a = { -5, -1, -1, 2, -2, -3 };Â Â Â Â int n = a.Length;Â
    // Function to find the longest subarray    Console.Write(longestAlternatingSubarray(a, n));}}Â
// This code is contributed// by Akanksha Rai |
PHP
<?php// PHP program to find the longest alternating// subarray in an array of N numberÂ
// Function to find the longest subarrayfunction longestAlternatingSubarray($a, $n){         // Length of longest alternating    $longest = 1;    $cnt = 1;Â
    // Iterate in the array    for ($i = 1; $i < $n; $i++)     {Â
        // Check for alternate        if ($a[$i] * $a[$i - 1] < 0)         {            $cnt++;            $longest = max($longest, $cnt);        }        else            $cnt = 1;    }    return $longest;}Â
// Driver Code$a = array(-5, -1, -1, 2, -2, -3 );$n = sizeof($a);Â
// Function to find the longest subarrayecho longestAlternatingSubarray($a, $n);Â
// This code is contributed by akt_mit?> |
Javascript
<script>// JavaScript program to find the longest alternating // subarray in an array of N number Â
// Function to find the longest subarray function longestAlternatingSubarray(a, n) { Â
    // Length of longest alternating     let longest = 1;     let cnt = 1; Â
    // Iterate in the array     for (let i = 1; i < n; i++) { Â
        // Check for alternate         if (a[i] * a[i - 1] < 0) {             cnt++;             longest = Math.max(longest, cnt);         }         else            cnt = 1;     }     return longest; } Â
/* Driver program to test above functions*/Â Â Â Â let a = [ -5, -1, -1, 2, -2, -3 ]; Â Â Â Â let n = a.length; Â
    // Function to find the longest subarray     document.write(longestAlternatingSubarray(a, n)); Â
// This code is contributed by Surbhi Tyagi.</script> |
Output
3
Complexity Analysis:
- Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the number of elements in the array.
- Auxiliary Space: O(1), as we are not using any extra space.
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



