Given an array containing positive and negative elements, find a subarray with alternating positive and negative elements, and in which the subarray is as long as possible.

The Longest Alternating Subarray problem differs from the problem of finding the Longest Alternating subsequence. Unlike a subsequence, a subarray is required to occupy consecutive positions within the original array.

 
For example, consider array { 1, -2, 6, 4, -3, 2, -4, -3 }. The longest alternating subarray is { 4, -3, 2, -4 }. Note that the longest alternating subarray might not be unique.

Practice this problem

We can easily solve this problem in linear time using similar logic as Kadane’s algorithm. The idea is to maintain the longest alternating subarray “ending” at each given array index. This subarray can be a single element (if the previous element has the same sign) or consists of one more element than the longest alternating subarray ending at the previous index (if the previous element has an opposite sign).

The algorithm can be implemented as below in C++, Java, and Python:

C++


Download  Run Code

Output:

The longest alternating subarray is [4, -3, 2, -4]

Java


Download  Run Code

Output:

The longest alternating subarray is [4, -3, 2, -4]

Python


Download  Run Code

Output:

The longest alternating subarray is [4, -3, 2, -4]

The time complexity of the above solution is O(n) and requires O(n) extra space, where n is the size of the input.

 
Because of the way the algorithm uses optimal substructures (the maximum subarray ending at each position is calculated simply from a related but smaller and overlapping subproblem: the maximum subarray ending at the previous position), this algorithm can be viewed as a simple example of dynamic programming.